我正试图从JavaScript调用服务器端,然后将字符串数组传递回JavaScript,但遇到问题。
// Call the server-side to get the data.
$.ajax({"url" : "MyWebpage.aspx/GetData",
"type" : "post",
"data" : {"IdData" : IdData},
"dataType" : "json",
"success": function (data)
{
// Get the data.
var responseArray = JSON.parse(data.response);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
在ASP。. Net服务器端,我有:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetTip(String IdTip)
{
int iIdTip = -1;
String[] MyData = new String[2];
// Formulate the respnse.
MyData[0] = "My header";
MyData[1] = "My body";
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(MyData);
return strResponse;
}
我可能把事情搞混了,因为我对JSON还是个新手。
更新错误码:
Exception was thrown at line 2, column 10807 in http://localhost:49928/Scripts/js/jquery-1.7.2.min.js
0x800a03f6 - JavaScript运行时错误:无效字符
堆栈跟踪:解析JSON[jquery-1.7.2.min.js] Line 2
我有什么问题?
我将ajax调用脚本修改为:
// Call the server-side to get the data.
$.ajax({
url: "WebForm4.aspx/GetTip",
type: "post",
data: JSON.stringify({ IdTip: "0" }),
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
注意,我添加了contentType: 'application/json'
并更改了
var responseArray = JSON.parse(data.response);
var responseArray = JSON.parse(data.d);
这纯属猜测。但看看这是不是你得到的:-在您的Ajax
调用中,您的数据类型是json,并查看您返回json字符串的方法。因此不需要执行JSON.parse(data.response)。相反,看看下面的方法是否适合你。我也没有看到一个response
对象在你的Json,相反,它只是一个数组。所以它一定是在尝试解析undefined
var strHeader = data[0];
var strBody = data[1];