【问题标题】:$.ajax & passing data to .asmx webservice$.ajax & 将数据传递给 .asmx webservice
【发布时间】:2011-09-28 02:57:31
【问题描述】:

我很困惑为什么会这样。

我似乎无法通过$.ajax 成功传递数据,URL 被全部弄乱了,而不是在查询字符串中传递数据。

为了简洁起见,我已经清理了代码,见下文。

网络服务(使用 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.

【问题讨论】:

    标签: c# ajax web-services jquery


    【解决方案1】:

    尝试改变

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

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

    【讨论】:

    • 或者您可以将contentType 更改为application/json。 (encosia.com/…)
    • @xdazz 所以“数据”部分只是附加到 URL 上吧?嗯,很高兴知道哈哈,非常感谢!
    • @Marko 如果它是一个字符串是的。如果它是一个对象没有。如果您在 { 之前和之后 } 删除 pling,您会看到与您描述的行为不同的行为
    • @Marko 如果您删除了 pling 和双 pl​​ing 即 { country:country, ...}
    【解决方案2】:

    在选项列表中添加 "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);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2011-07-23
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多