2011-03-02 34 views
0

反正我有可以发布的时候同时处理JSON和HTML返回类型的jQuery AJAX:你可以在同一个Ajax调用中处理json和html数据类型吗?

例如,这AJAX调用需要的html回

$.ajax({ 
      type: "POST", 
      url: url 
      data: data, 
      dataType: "html", 
      success: function (response) { 
       var $html = "<li class='list-item'>" + response + "</li>"; 
       $('#a').prepend($html);       
      }, 
      error: function (xhr, status, error) { 
       alert(xhr.statusText); 
      } 
     }); 

但我想修改它,这样我可以返回如果存在模型错误,则为json对象。所以我可以这样做:

success: function (response) { 
      if (response.Error){ 
       alert(response.Message); 
      } else { 
       var $html = "<li class='list-item'>" + response + "</li>"; 
       $('#a').prepend($html);       
      } 

这可能吗?

回答

3

对于您的第一个案例,只需在response.Message字段中输入html即可。返回包装在json对象中的html并不罕见,因此可以轻松添加状态码。

相关问题