服务器端未触发带有JSON数组的AJAX调用

本文关键字:数组 AJAX 调用 JSON 服务器端 | 更新日期: 2023-09-27 18:22:15

我试图使用jquery ajax将json数组传递给我的代码后台。

效果

如果我使用带有空json字符串("{}")的jQuery .ajax()调用我的codeehind函数,那么我的code-hind函数将被触发而不会出现问题。

我要做的

如果我把Json字符串放在jQuery .ajax()的"data"属性中,然后用字符串参数创建一个代码隐藏函数,它就不会再被触发了。

这是我的代码:

客户端

function SendAjax() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/MyFunction",
        data: '{"foo":"bar"}',
        dataType: "json",
        success: function (msg) {
           //DO Somtething
        },
        error: function (xhr, status, error) {
            //DO Somtething
        }
    });
}

服务器端

[WebMethod]
public static string MyFunction(string jsonData)
{   
   //Do something
   return "test";
}
  • 我的json数组格式正确
  • 我有一个静态函数
  • 我有[WebMethod]

我是不是错过了什么?

服务器端未触发带有JSON数组的AJAX调用

试试这个100%工作的

function SendAjax() {
            var city = "ABC";
            $.ajax({
                type: "POST",
                url: "Default4.aspx/MyFunction",
                data: "{jsonData:" + JSON.stringify(city) + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                   alert(msg.d);
                },
                error: function (xhr, status, error) {
                    //DO Somtething
                }
            });
        }


[WebMethod]
    public static string MyFunction(string jsonData)
    {
        //Do something
        return "test";
    }