简体   繁体   中英

JQuery AJAX trying to parse XML even with “dataType” : “JSON”

As the title suggests, I have the following:

$.ajax({
  "url" : ...
, "type" : "GET"
, "dataType" : "JSON"
, "success" : function(response_data) {
    that.data = response_data;
    success(response_data);
  }
, "onerror" : function(data) {
    console.log(JSON.stringify(data));
  }
});

But when I run it, I get

XML Parsing Error: syntax error Location: moz-nullprincipal

Looking at firebug, I see that the request was

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Cache-Control   max-age=0
Connection  keep-alive
Host    localhost:8888
Referer http://localhost:8888/
User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101       Firefox/13.0.1
X-Requested-With    XMLHttpRequest

Any ideas?

Change "JSON" to lowercase "json" first. But this is the type that jQuery is expecting back from the server, it's not necessarily what the server will send.

Are you sure that the server is returning JSON? Worth a double-check. Have you looked at the response in Fiddler? If it's XML it's the server's issue, not the script's.

Ok great thanks to everyone tried to answer this.

But it turns out, as usual, I noob'ed out here.

The XML parsing error shown in firebug is not actually an error with the code, and firebug's failed attempt to guess it's XML and parse it.

My problem was elsewhere in the program and it was solved.

Upper vs lower case "JSON" did not make a difference.

Max

The real problem is that your server is not setting the 'Content-type' header. Set it to 'application/json'.

For example in node.js:

res.setHeader('Content-type', 'application/json');

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM