我必须将二维数组传递给在 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/