Is there a way to convert the result retrieved from an ajax call into a JavaScript array without relying on jQuery?
Alternatively, would it suffice to simply loop through the JSON array without converting it into a JavaScript array?
Currently, I just need to display the results obtained from the ASMX service. Using jQuery is not an option.
Data received from the request:
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 Code
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# Code
[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);
}
}