I'm using an AJAX request. This is the first time I'm using JSON or any of it's methods. The ajax utility returns an argument to the onreadystatechange callback as the responseText开发者_StackOverflow or responseXML of the file I'm requesting. Using a simple info.txt
and request.responseText
will work fine but when I try info.js
and JSON.parse
it returns "Unexpected token ILLEGAL" when I've checked multiple times that my syntax is correct. Here is the JSON:
JSON:
{
first: 1,
second: 2
}
JSON.parse()
is very strict in grammar. The key/value pairs should have the form:
string:value
So the "first" and "second" should be string in a JSON object. Change your JSON to following code and it should be right
{
"first": 1,
"second": 2
}
You seem to already be using jQuery in your success callback. jQuery also has methods to perform AJAX requests such as $.ajax
rendering your AJAX custom function pretty useless. In your case you seem to be requesting a javascript file (.js) which is different than JSON. So:
(function() {
$.getScript('json.js', function(result) {
// TODO: do something with the result
});
})();
or if it is JSON:
(function() {
$.getJSON('json.js', function(result) {
// TODO: do something with the result
});
})();
This being said you could still continue to use your method but JSON.parse(e)
will always fail if your json.js
doesn't contain a valid JSON string. To verify that it contains a valid JSON string you could validate it on http://jsonlint.com
精彩评论