不使用jQuery解析JSON
本文关键字:解析 JSON jQuery | 更新日期: 2023-09-27 18:30:09
我想将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)
您确实意识到JSON是javascript的有效子集,不是吗?
这意味着将JSON字符串序列化为Javascript对象非常简单:
var json = MakeAjaxRequestHere() ;
var deseralizedJsonObject = eval( '(' + json + ')' ) ;
不过,需要注意的是,除非您信任JSON的来源,否则eval会有一些风险,因为它会评估任何javascript程序。看见http://www.json.org/js.html了解更多信息。