I've written the following code:
$.get('http://example.com/books.json', function (data) {
// ...
});
books.json
is a list of objects of new books, sometimes jQuery parses the JSON data into object, but sometimes leaves as string (probably because of some international/utf8 issues). In that case I call JSON.parse() myself and get valid JSON object that works.
I've a question therefore - what is the correct way to force JSON.parse when doing a GET request with jQuery? I don't want jQuery to guess if it's JSON data or not. How could I make jQuery think it's string always, and I will always call JSON.parse myself?
$.get
takes an optional dataType
argument, and you can specify text
to force it to return the data as a plain string.
$.get('http://example.com/books.json', function (data) {
// ...
}, "text");
Otherwise, it looks at the Content-type:
header in the response to determine the datatype.
If you want to force a JSON parse, you can specify json
, or you can use $.getJSON
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments