gpt4 book ai didi

c# - 不用 jQuery 解析 JSON

转载 作者:行者123 更新时间:2023-11-30 17:52:50 27 4
gpt4 key购买 nike

我想将从 ajax 调用获得的结果转换为 JavaScript 数组。如何在不使用 jQuery 的情况下做到这一点?

或者也可以只循环 json 数组而不转换为 JavaScript 数组。

现在我只需要提醒我从 ASMX 服务获得的结果。使用 jQuery 不是任何选择。

请求数据:

string xmlns="http://tempuri.org/"
[{"Action":"Test1","Target":"#cTarget","Payload":"Hello"},{"Action":"Test2","Target":"#cTarget","Payload":"World"}]
string

[
{
"Action":"Test1",
"Target":"#cTarget",
"Payload":"Hello"
},
{
"Action":"Test2",
"Target":"#cTarget",
"Payload":"World"
}
]

JavaScript 代码

  var httpRequest;

function makeRequest(url, input) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}

if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var results = httpRequest.responseText;
var asJavaScriptArray = JSON.parse(results);

}
}
//}
};

httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/json');
httpRequest.send(input);
}

var endpointAddress = "Core/RecipeDemo.asmx";
var url = endpointAddress + "/Base";
makeRequest(url, "{}");`

C#代码

[System.Web.Script.Services.ScriptService]
public class RecipeDemo : System.Web.Services.WebService
{

[WebMethod]
public string Base()
{

List<Recipe> listOfRecipe = new List<Recipe>();
JavaScriptSerializer jss = new JavaScriptSerializer();

listOfRecipe.Add(new Recipe {Action = "Test1", Payload = "Hello", Target = "#cTarget"});
listOfRecipe.Add(new Recipe {Action = "Test2", Payload = "World", Target = "#cTarget"});

return jss.Serialize(listOfRecipe);
}
}

最佳答案

你应该已经有了一些东西可以将 JSON 字符串作为对象

JSON.parse(myJsonString)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

从一个对象返回到字符串到JSON.stringify(myObject)

关于c# - 不用 jQuery 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18624304/

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