开发者

$.ajax & passing data to .asmx webservice

I'm quite confused as to why this is happening.

I can't seem to pass data successfully via $.ajax, the URL gets all mangled up instead o开发者_JS百科f the data being passed in a query string.

I've cleaned up the code for brevity, see below.

Webservice (using 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);
    }
});

Resulting URL and Error (in Firebug)

http://example.com/Test.asmx/TestMethod?{%22country%22:%22NZ%22,%22city%22:%22AK%22}
System.InvalidOperationException: Missing parameter: country.


Try to change

data: '{"country":"' + country + '","city":"' + city + '"}'

To

data: "country="+country+"&city="+city


Adding a "contentType" property to the options list would be the easiest change in my mind.

I also use JSON.stringify() to reduce the introduction of quotation errors.

$.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);
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜