代码之家  ›  专栏  ›  技术社区  ›  Andy

jquery ajax-处理两种独立的响应类型

  •  0
  • Andy  · 技术社区  · 7 年前

    我正在开发一个应用程序(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 .没关系。

    但我该怎么处理第二种情况呢?如果我添加以下代码:

    // 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

    我看着 dataType 在jquery上 ajax documentation 但不确定这是否相关,因为我实际上收到了两个基于结果的独立内容类型。

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

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

    因此,HTML在情况1中工作得更好,而JSON在2中工作得更好。

    有人能给我建议吗?

    2 回复  |  直到 7 年前
        1
  •  0
  •   collapsar    7 年前

    正如您所观察到的,在案例2中,您将在JSON forat中收到一个响应。当您的代码被传递给 response 参数。用 JSON.stringify 您可以用HTML代码显示:

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

    请注意,这不是一个很好的视图,因为JSON结构没有转换为等效的HTML子树。

    看看 this fiddle 看到一个成熟的例子。

    有一些库可以将JSON结构转换为交互式HTML,例如。 JSTree (可能对您的用例造成过度杀伤力)。

        2
  •  0
  •   Andy    7 年前

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

    这里真正的问题是: 是否有方法确定响应类型是HTML还是JSON .done()

    是的,有。记录如下: 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 .如果发生错误,并且JSON从Ajax脚本发回,则可以根据返回的JSON将错误消息写入相应表单字段的下面。