javascript - 从 jquery ajax 传递数组到代码后面

标签 javascript jquery asp.net ajax

我必须将二维数组传递给在 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 数组传递给代码隐藏但无法实现。一个简单的调用 wihtout 数组为我工作就像

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

在代码后面

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

传递数据时出现问题。你能帮助我如何将它传递给数组吗?

最佳答案

在 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)

关于javascript - 从 jquery ajax 传递数组到代码后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15699395/

相关文章:

jquery - 使用函数获取 jQuery 中元素的 id

c# - 如何将CSS应用于表格行

asp.net - 异步操作超过页面超时(尝试将 HttpRequestMessage 与 ASP.NET WebForms 页面一起使用)

javascript - Selenium - 焦点和模糊在 Firefox 上随机失败

javascript - 如何使用 Google Charts API 柱形图绘制单个数据点?

javascript - 使用 jQuery 将事件与 for 循环绑定(bind)到多个元素

asp.net - http handler 接口(interface)中 bool IsReusable 的意义

javascript - D3.js: "Uncaught SyntaxError: Unexpected token ILLEGAL"?

javascript - 是否可以一起使用 TypeScript 和 Babel

javascript - 在更改单选按钮状态时显示提交按钮...怎么样?