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 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
}
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 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
}
Share
Improve this question
edited Sep 11, 2011 at 17:56
David G
asked Sep 4, 2011 at 13:55
David GDavid G
96.8k41 gold badges172 silver badges257 bronze badges
4
- 3 first at all, take a look to jQuery way of AJAX calls, if you are using it, why are you writing own ajax function ? – SergeS Commented Sep 4, 2011 at 13:58
- 2 This would help if you included the JSON string you are trying to parse in the question ;) – Arnaud Le Blanc Commented Sep 4, 2011 at 14:02
- 2 JSON.parse() should be JSON.parse(e) – Gabriel Llamas Commented Sep 4, 2011 at 14:05
- 1 Firstly, throw away your AJAX() function and use JQuery's built-in ones instead. You're just reinventing the wheel. Secondly, if you're getting a parse error when it tries to read your JSON code, then we probably need to see your JSON code so we can see what the parse error is. – Spudley Commented Sep 4, 2011 at 14:08
2 Answers
Reset to default 11JSON.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