[英]$.ajax & passing data to .asmx webservice
我很困惑为什么会这样。
我似乎无法通过$.ajax
成功传递数据,URL全部被破坏,而不是在查询字符串中传递的数据。
为简洁起见,我清理了代码,见下文。
Web服务(使用GET)
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string TestMethod(string country, string city)
{
return country + city;
}
jQuery的
$.ajax({
url: "Test.asmx/TestMethod",
type: "GET",
data: '{"country":"' + country + '","city":"' + city + '"}',
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
产生的URL和错误(在Firebug中)
http://example.com/Test.asmx/TestMethod?{%22country%22:%22NZ%22,%22city%22:%22AK%22}
System.InvalidOperationException: Missing parameter: country.
试着改变
data: '{"country":"' + country + '","city":"' + city + '"}'
至
data: "country="+country+"&city="+city
将“contentType”属性添加到选项列表将是我脑海中最容易的变化。
我还使用JSON.stringify()
来减少引用错误的引入。
$.ajax({
url: "Test.asmx/TestMethod",
type: "GET",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ country: country, city: city }),
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.