Alexander Zhukov Alexander Zhukov - 5 months ago 60
jQuery Question

jQuery getJSON syntax error on a valid JSON

I have the following valid json data

[
{
"title":"title1",
"value":12234
},
{
"title":"title2",
"value":"some text"
},
{
"title":"title3",
"value":"12qwerty234"
},
{
"title":"title4",
"value":123.5
}
]


I am using jQuery to load it with the next code

$(document).ready(function(){
$.getJSON("json.js", {},function(result){
$.each(result, function(i, obj) {
$("form").append($('<label for="'+i+'">'+obj.title+'</label>'));
$("form").append($('<input id="'+i+'" value="'+obj.value+'" type="text"/><br>'));
});
});
});


My problem is, that I am getting a syntax error in Firefox. I load json.json as a local file.
Here is a screenshotenter image description here

Note, that form has been generated successfully.

Edit :
Here is another screenshot from Chrome when running python
SimpleHTTPServer
:
enter image description here

Answer

The reason this happens is because you're using a local file, so a mime type of "text/xml" is implied and hence Firefox will try to parse it as XML into .responseXML of the underlying XHR object. This of course fails.

You may just ignore this, or specify the mimeType yourself:

$.ajax({
    dataType: "json",
    url: "json.json",
    mimeType: "application/json",
    success: function(result){
        $.each(result, function(i, obj) {
            $("form").append($('<label for="'+i+'">'+obj.title+'</label>'));
            $("form").append($('<input id="'+i+'" value="'+obj.value+'" type="text"/><br>'));
        });
    }
});

PS: Using plain XHR you would use overrideMimeType()

Comments