naazia
02-02-2010, 04:29 AM
Hi,i was trying to retrieve value from server in JSON format in AJAX but it is not retrieving any thing it is just showing no output
Javascript:
xhr1.open("GET", "Jsonex.aspx", true);
xhr1.onreadystatechange = function() {
if (xhr1.readyState == 4) {
document.getElementById("div1").innerHTML = "inside the function";
var jsonT = eval("(" + xhr1.responseText + ")");
var i=jsonT.somavar.abc;
document.getElementById("div1").innerHTML = "<h1>" + "hi" + "</h1>";
document.getElementById("div1").innerHTML = "<h1>" + i +"</h1>";
}
}
xhr1.send(null);
Asp.net server page:
var r = "{'somevar':{'abc':'blue','color':'red'}}";
Response.Write(r);
iam a missing anything while retrieving ,plz help me,Thank you
Dormilich
02-02-2010, 04:30 PM
shouldn’t be the return value {'somevar':{'abc':'blue','color':'red'}}?
naazia
02-02-2010, 04:53 PM
i got the desired output,i was trying to put the JSON data in .aspx file i tried to put the JSOn in .txt file n everything is working fine,any how Thank you so much
i got the desired output,i was trying to put the JSON data in .aspx file i tried to put the JSOn in .txt file n everything is working fine,any how Thank you so much
Right, just so long as you understand that the JSON data can be returned from a dynamic server-side script as well, you just have to use the proper ASP code to output that string. Otherwise, if it's stored in a text file, then yes by all means use the .txt extension or it the request will attempt to call it as an ASP script, not plain text.
naazia
02-02-2010, 07:54 PM
Is there any way by which i can send the request and get response from Server side script not approaching directly to .txt file as i did above?
i believe i need to have some parser which could change the response from JSON format to string, so that i can send to client,but i couldn't find the parsers online,is thr any other way to achieve this?
Thank you
naazia
02-02-2010, 10:32 PM
JavaScriptSerializer js = new JavaScriptSerializer();
Class1 obj = new Class1();
obj.ID = 1;
obj.Username = "aaa";
obj.date1 = "2/2/2010";
obj.msg = "Hi,How r u doing?";
string json = js.Serialize(obj);
Response.Write(json);
If i serialize this way,the data is send in string form but client is unable to deserialize back to JSON using the eval(),what can i do now?
Thank you
What is the actual output of that code?
You do realize you can simply return a string like:
{
"items": [
"item1" : { "property": "something" },
"item2" : { "property": "other thing" }
]
}
That's a valid JSON object.
You aren't required to use any specific function that creates a JSON object, just return plain text, and force a header of "Content-Type: text/javascript".
naazia
02-04-2010, 12:23 AM
I try to send in string format but there no result,the Output is blank,what can i do now to get the required o/p