开发者

jQuery $.post - how to call a callback function if $.post fails and or if the response is not the type you expect

Here's the thing, I have a jquery click event handler, that calls a post on click.

The type that it expects (4th parameter of $.post()) is "json". However, on the server side; there are two responses to the post: it's either json or html response. The problem is, if it returns html, the 开发者_StackOverflow中文版callback function isn't called (because the $.post expects a json?).

How can I react to this? I want something that if the server side script returns a json, execute callback, otherwise do another. Is that possible? Can I check the response type with $.post?


You'll most likely want to use the generic jquery.ajax function. In particular the dataType: 'text' property should allow you to parse your return value in whatever method works for you. You can also use the parseJSON function

$.ajax({
  url: 'url',
  type: 'post'
  dataType: 'text',
  success: function(text) {
     if  (json) {
         var obj = $.parseJSON(text);
     } else {
         var html = $(text);
     }
  }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜