开发者

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 t开发者_运维技巧his 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜