【问题标题】:Pass array to code behind from jquery ajax将数组传递给 jquery ajax 后面的代码
【发布时间】:2013-03-19 22:15:22
【问题描述】:

我必须将二维数组传递给在 asp.net 网页后面的代码中编写的页面方法我有一个变量 objList 作为二维数组。我使用以下代码实现了这一点,但没有成功,并且没有调用页面方法。

JAVASCRIPT

function BindTable(objList) {

    $.ajax(
    {
           url: "CompCommonQues.aspx/SaveData",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           type: "POST",
           data: { data: objList },
           success: function (data) {
           //Success code here
    },
    error: function () { }
    });
  }

.CS 文件隐藏代码

 [WebMethod]
public static string SaveData(string[,] data)
{
    string[,] mystring = data;
    return "saved";
}

有像 JSON.stringify(objList) 这样的方法将 json 数组传递给后面的代码,但无法实现。一个对我有用的没有数组的简单调用,就像

data: "{ 'data':'this is string' }",

在后面的代码中

[WebMethod]
public static string SaveData(string data)
{
    string mystring = data;
    return "saved";
}

传递data 有问题。你能帮我如何将它传递给数组吗?

【问题讨论】:

    标签: javascript jquery asp.net ajax


    【解决方案1】:

    在 JavaScript 中尝试正确的 JSON 表示法

    var objList = new Array();
    objList.push(new Array("a","b"));
    objList.push(new Array("a", "b"));
    objList.push(new Array("a", "b"));
    
       $.ajax({
           type: "POST",
           url: "copyproduct.aspx/SaveDate",
           data: "{'data':'" + JSON.stringify(objList) + "'}",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (msg) {
                alert(msg.d);
           }
       });
    

    在后面的代码中,您可以使用 JavaScriptSerializer (System.Web.Script.Serialization) 进行反序列化

    [WebMethod()]
    public static string SaveDate(string data)
    {
        JavaScriptSerializer json = new JavaScriptSerializer();
        List<string[]> mystring = json.Deserialize<List<string[]>>(data);
        return "saved";
    }
    

    我不得不反序列化为字符串数组的通用列表,因为您无法反序列化为字符串(检查:http://forums.asp.net/t/1713640.aspx/1

    【讨论】:

    • 当我调试代码时,Web 方法没有命中。函数背后的代码需要进行哪些更改。
    • 您传递的字符串如下: { data: [["a","b"],["a","b"],["a","b"]] } .所以需要将参数从string(,)改为string,并使用System.Web.Script.Serialization.JavaScriptSerializer反序列化为string(,)。我会制定这个例子。
    • 我已经按照您的建议更改了我的代码,创建了数组,但是方法后面的代码仍然没有命中。
    • 您是否复制了代码?你在使用萤火虫吗?你能看到“Net”>“XHR”下显示的是什么消息吗?我已经在我的项目中对其进行了测试,并且可以正常工作。
    • 错误是internal server error 在帖子部分{ data: [["123","1"],["153","2"],["123","1"],["123","1"],["153","2"],["123","1"],["123","1"],["153","2"],["123","1"]] } 和消息是"Type 'System.String' is not supported for deserialization of an array."
    猜你喜欢
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2017-07-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多