jQuery ajax-处理2种不同的响应类型

时间:2018-07-12 11:24:29

标签: jquery ajax

我正在开发一个应用程序(jquery 3.2.1),在该应用程序中进行ajax调用可能导致以下情况之一-提供服务器给出HTTP 200 OK响应:

  1. HTML返回。这是期望的结果,因为它是对有效请求的“内容”响应。

  2. 如果存在基于请求数据的验证错误,则会返回JSON错误。

我拥有的ajax代码如下:

$.ajax({
  url: $('#searchRegulations').attr('action'),
  type: 'post',
  cache: false,
  data: $('#searchRegulations').serialize()
}).done(function (response) {
    if (response) {
      // Display response (point 1)
      $('main .content').hide();
      $('#ajaxContent').html(response).show();
      return false;
    } else {
        // Handle JSON error (point 2)    
    }
});

正如我在上面的评论中提到的,如果情况1发生(返回HTML),则将其写入#ajaxContent。很好。

但是对于情况2我该怎么办?如果我添加以下代码:

// Handle JSON error (point 2)  
$('main .content').hide();
$('#ajaxContent').html(response).show();

#ajaxContent内没有任何内容。

这是因为未返回HTML吗?

每个响应头都不同:

  1. Content-Type: text/html; charset=UTF-8

  2. Content-Type: application/json; charset=UTF-8

我在jquery ajax documentation上查看了dataType,但不确定是否相关,因为我实际上是根据结果收到2个单独的Content-Type。

在方案2中返回JSON的原因是因为有一些代码(未显示)可以在每个字段下方写入错误消息,例如

`{rf_keywords: {length: "Search keywords must under 1500 characters in length."}}`

因此HTML在情况1下效果更好,而JSON在情况2下效果更好。

请有人提供建议吗?

2 个答案:

答案 0 :(得分:0)

如您所见,在案例2中,您会在json forat中收到响应。当您将代码传递给response参数时,这应该已经被解析。使用JSON.stringify再次将其转换为字符串,您将能够以html代码显示它:

$('#ajaxContent').html(JSON.stringify(response)).show();

请注意,由于JSON结构没有转换为等效的html子树,因此这不是一个漂亮的视图。

看看this fiddle可以看到完整的示例。

有一些库可以将JSON结构转换为交互式html,例如。 JSTree(对于您的用例而言,可能会适得其反。)

答案 1 :(得分:0)

好,我在回答自己的问题。

这里的真正问题:有没有一种方法可以确定.done()

中的Response类型是HTML还是JSON。

是的。在此处记录:jquery how to check response type for ajax call

所以我的最终ajax代码如下:

$.ajax({
    url: $('#searchRegulations').attr('action'),
    type: 'post',
    cache: false,
    data: $('#searchRegulations').serialize()
 }).done(function (response, status, xhr) {

            // The ajax handler can return either HTML or JSON. So we need to know what's been returned.
            var ct = xhr.getResponseHeader("content-type") || "";

            // HTML response == content to display. No validation error.
            if (ct.indexOf('html') > -1) {
                if (response) {
                    $('main .content').hide();
                    $('#ajaxContent').html(response).show();
                    return false;
                }
            }
            // JSON response. Validation error(s) occurred.
            if (ct.indexOf('json') > -1) {
                $.each(response, function(i, v) {
                    $.each(v, function(k, m) {
                         var msg = '<span class="help-block">'+m+'</span>';
                         $('input[name="' + i + '"]').parent().after(msg);
                         $('input[name="' + i + '"]').closest('.form-group').addClass('has-error');
                    });
                });
            }  
});

执行此操作意味着您可以检查HTML是否已返回-在这种情况下,请在#ajaxContent中显示它。如果发生错误,并且从ajax脚本发送回JSON,则可以根据返回的JSON将错误消息写在适当的表单字段下。