I am trying to parse a response of a string which is a json string. In another page of my web app following code is working fine. but its not working for my current page i am working with. Following is the code:
$.ajax({
type: 'POST',
url: 'http://mywebapp.com/sendnames',
data: {},
success: function(result) {
alert('result: '+result);
var obj = jQuery.parseJSON(result);
alert('obj: '+obj);
// doing rest of stuff
}
});
first alert comes and shows right result. result is:
[
"Richard",
"Eric",
"John"
]
but second alert does not come. i checked it, its a valid json. why can not i parse this json with jQuery.parseJSON(). Thanks in advance.
Try to add return type: dataType : json
$.ajax({
type: 'POST',
url: 'http://mywebapp.com/sendnames',
data: {},
dataType:'json',
success: function(result) {
console.log('result: '+result);
// doing rest of stuff
}
});
"json":
Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.) "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. http://api.jquery.com/jQuery.ajax/
Replace $.ajax
by $.getJSON
. This is guaranteed to trigger $.parseJSON
internally, so result
will already be the desired JS object.
$.getJSON({
type: 'POST',
url: 'http://mywebapp.com/sendnames',
data: {},
success: function(obj) {
alert('obj: '+obj);
// doing rest of stuff
}
});
Try with adding dataType:'text'
, it will return string as result. and your code will run as you expect.
You're parsing an object. You parse strings, not objects; jQuery.parseJSON only takes strings.
Because $.ajax
already parsed the data, result
is Javascript object not a string. parseJSON
expects a string parameter.
FROM DOCS (more on .ajax()
data types here ):
The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses jQuery.parseJSON() when the browser supports it; otherwise it uses a Function constructor
.
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.