我想将从 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);
}
}