I am facing problem in getting the variables from my response string. My response is like this:
responseText = {'page':'2','endOfPage':'yes','content':'abc'}
alert(responseText.page);
is returning undefined, can anyone suggest how to do it??
Your problem is that your responseText is in fact a string ( responseText = "{'page':'2','endOfPage':'yes','content':'abc'}";
). You first have to parse it to create an object, this fails though because you are using single quotes, which are not valid JSON - you'll need to use double quotes for resolving the problem:
var json= "{ \"page\": 2, \"endOfPage\": \"yes\", \"content\": \"abc\" }";
var obj = JSON.parse(json);
alert(obj.page);
If you can't change the JSON-generator implementation to return a response with double quotes, try to replace every single quote into a double quote like this:
var invalidJson = "{'page':'2','endOfPage':'yes','content':'abc'}";
validJson= invalidJson.replace(/\'/g, "\"");
var obj = JSON.parse(validJson);
alert(obj.page);
responseText = '{"page":"2","endOfPage":"yes","content":"abc"}';
responseText = jQuery.parseJSON(responseText);
alert(responseText.endOfPage);
responseText = '{"page":"2","endOfPage":"yes","content":"abc"}'; alert(JSON.parse(responseText).page);
which is supported in some modern browsers for parsing JSON into a native js object
You need to use the eval function to convert json to object:
responseText = {'page':'2','endOfPage':'yes','content':'abc'}
var responseObject = eval(responseText);
alert(responseObject.page);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.