简体   繁体   中英

How do I handle a JSON request returning a String in JQuery?

New to json/jQuery so sorry if this has an obvious answer.

I'm doing an ajax request in jQuery that's something like:

$.ajax({
  url: theURL,
  dataType: 'jsonp',
  type: 'get',
  success: function(data) {
    alert("it's there");
  }
});

The request asks whether a given object is in a database. If it is, it returns something of the format:

{
  "text": "duck",
  "canonical_name": "duck",
  "language": {
    "id": "en"
  }
}

However, if the object isn't there, it returns:

Not Found

As in...literally that exact string, not in any kind of json format as far as I know. Is there any way I can get my ajax to detect this? Right now it doesn't even seem to be acknowledging that it got anything back in the latter case.

The json code wasn't written by me. It can possibly be fixed if this is not the correct format and there's absolutely nothing I can do from my end to work with this, but I'd really like to try to find some kind of workaround if possible.

Thanks very much!

You remove the dataType option and in callback :

success: function(data) {
  alert("it's there");
  var myJSON = eval(data);
}

Now you can get the data as an object and use like :

myJSON.language.id

@Aneesh Not sure that you want to remove the dataType option BUT you can still parse the data in the success callback. I'd use JSON.stringify() or even better: $.parseJSON(data) to avoid the eval downsides that @Lowgain pointed out. You'd end up with:

success: function(data) {
    var myJSON = $.parseJSON(data);
}

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