从jquery调用web服务

问题描述:

我需要从jQuery调用Web服务,当我把下面的代码击中断点,但它没有到达Web服务......这个代码有什么问题吗?从jquery调用web服务

function searchItems() { 

$("#txtSectionName").autocomplete({ 
    source: function (request, response) { 
     $.ajax({ 
      url: "/DataService.asmx/SearchSections", 
      data: "{'searchTerm' : '" + $("#txtSectionName").val() + "'}", 
      dataType: "json", 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      dataFilter: function (data) { return data; }, 
      success: function (data) { 
       response($.map(data.d, function (item) { 
        return { 
         value: item.Name 
        } 
       })) 
      }, 
      error: function (XMLHttpRequest, textStatus, errorThrown) { 
       alert(textStatus); 
      } 
     }); 
    }, 
    minLength: 1 
}); 

}

+0

您发送的数据不是JSON。在JSON中,键和字符串值必须用双引号括起来。 Web服务可能因此无法处理请求。 – 2012-03-22 15:05:05

+0

@OP你可以分享网络服务方法代码... – Rafay 2012-03-22 15:07:40

+0

感谢你的回复Felix Kling和3nigma,现在工作正常....对于延迟 – shanish 2012-04-03 05:45:33

您的数据格式不正确。 jQuery将负责JSON编码。只需传递一个对象:

 $.ajax({ 
      url: "/DataService.asmx/SearchSections", 
      data: {searchTerm: $("#txtSectionName").val() }, 
      dataType: "json", 
      type: "POST", 
      success: function (data) { 
       response($.map(data.d, function (item) { 
        return { 
         value: item.Name 
        } 
       })) 
      }, 
      error: function (XMLHttpRequest, textStatus, errorThrown) { 
       alert(textStatus); 
      } 
     }); 
+1

jQuery不会将其转换为JSON。它会创建一个查询字符串,比如'searchTerm = value',而不是JSON。 – 2012-03-22 16:04:22

+0

不是查询字符串,因为这是一个POST请求。但你是对的,而不是JSON。我的意思是嵌套的url编码,Rails实例解码为Hash。但这取决于你在服务器端有什么... – Blacksad 2012-03-22 16:14:37

+0

感谢Blacksad,它的工作现在很好 – shanish 2012-04-03 05:46:26

有您在配置Web服务以接受来自跨域请求,见CORS,也尝试使用jsonp作为dataType可能解决问题...还网络服务通常服务于GET请求

+0

来自代码中的url,它不是跨域这里 – Blacksad 2012-03-22 15:13:58