gpt4 book ai didi

javascript - 将字符串数组从 ASP.NET 传递到 JavaScript

转载 作者:行者123 更新时间:2023-11-30 18:04:41 24 4
gpt4 key购买 nike

我试图从 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] 第 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);

关于javascript - 将字符串数组从 ASP.NET 传递到 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com