【问题标题】:An issue with jQuery $.isArrayjQuery $.isArray 的问题
【发布时间】:2018-03-09 12:29:08
【问题描述】:

我有这个 ajax 帖子,工作得很好,所以它运行函数 testdata 传递给它。

$("#formID").submit(function (event) {
    $('#postError').html('').hide();
    $('#postInfo').html('loading results').show();
    event.preventDefault();

    $.ajax({
                type: 'POST',
                url: $("#formID").attr('action'),
                data: $(this).serialize()
            })
            .done(function (data) {
                $('#postInfo').html('').hide();
                test(data);
            })
            .fail(function () {
                $('#postInfo').html('').hide();
                console.log(1);
           });
})

这就是问题所在,

function test(data) {
    console.log(data);
    if ($.isArray(data)){
        $('#postSuccess').html(data).show();
    }else {
        $('#postError').html(data).show();
    }
}

这是我在 console.log 中得到的:

 [{"a1":"1","a1amount":"300","a2":"2","a2amount":"300","a3":"3","a3amount":"300"
 ,"a4":"4","a4amount":"300","a5":"5","a5amount":"60"}, 
 {"b1":"6","b1amount":"75","b2":"7","b2amount":"75","b3":"8","b3amount":"75"}, 
 {"c1":"9","c1amount":"40","c2":"10","c2amount":"40","c3":"11","c3amount":"40"," c4":"12","c4amount":"40"}]

这是一个普通的 json 数组对还是我错了? 如果我是对的,那么我想知道它为什么运行 else 部分 如果我错了,那么我想知道函数或数组有什么问题。

【问题讨论】:

  • 我确定你得到的是一个字符串而不是一个数组。即:'[{"a1":"1","a1amount":"300","a2":"2","a2amount":"300","a3":"3","a3amount":"300" ,"a4":"4","a4amount":"300","a5":"5","a5amount":"60"}, {"b1":"6","b1amount":"75","b2":"7","b2amount":"75","b3":"8","b3amount":"75"}, {"c1":"9","c1amount":"40","c2":"10","c2amount":"40","c3":"11","c3amount":"40"," c4":"12","c4amount":"40"}]' - 但是,Console.log(data) 将其打印为对象。您需要先将字符串解析为对象。使用JSON.parse(data)
  • 是的,确实有效,谢谢。

标签: javascript arrays json ajax


【解决方案1】:

.serialize() 方法以标准 URL 编码表示法创建文本字符串。它可以作用于已选择单个表单控件的 jQuery 对象。

你的函数 test() 改变它以保持它的工作

function test(data) {
    var res = JSON.parse(data);
    console.log(res);
    if ($.isArray(res)){
        $('#postSuccess').html(data).show();
    }else {
        $('#postError').html(data).show();
    }
}

根本原因是你得到了字符串。

【讨论】:

    【解决方案2】:

    如果您可以控制服务器,最好的解决方案是在响应中包含 Content-Type: application/json 的标头。这样,$.ajax(...) 调用将知道在收到数据时如何处理您的数据。有关血腥细节,请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type

    如果您无权访问服务器端代码,您可以将名为dataType 的属性添加到您的 ajax 请求中,如下所示。这将避免需要JSON.parse(...) 所有回复。

    示例 1

    在此示例中,我将演示您的服务器当前正在做什么。示例 API 服务器返回正确的标头,因此我必须设置 dataType: 'html' 来模拟您的服务器。

    $.ajax({
        type: 'GET',
        url: 'https://jsonplaceholder.typicode.com/posts',
        dataType: 'html'
      })
      .done(function(data) {
        test(data);
      })
      .fail(function() {
        console.log(1);
      });
    
    function test(data) {
      console.log(data);
      if ($.isArray(data)) {
        console.log("array :-)")
      } else {
        console.log("no array :-(")
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    示例 2

    这是一个示例,演示如何设置 dataType: 'json' 以使回调中的数据与您的预期数据格式相匹配。

    $.ajax({
        type: 'GET',
        url: 'https://jsonplaceholder.typicode.com/posts',
        dataType: 'json' // set dataType to 'JSON'
      })
      .done(function(data) {
        test(data);
      })
      .fail(function() {
        console.log(1);
      });
    
    function test(data) {
      console.log(data);
      if ($.isArray(data)) {
        console.log("array :-)")
      } else {
        console.log("no array :-(")
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    【讨论】:

      【解决方案3】:
      function test(data) {
          console.log(data);
      
          if ($.isArray(JSON.parse(data))){
              $('#postSuccess').html(data).show();
          }else {
              $('#postError').html(data).show();
          }
      }
      

      使用 JavaScript isArray() 函数代替 jQuery。它支持所有类型的浏览器。这里我添加示例代码

      function myFunction() {
        var fruits = ["Banana", "Orange", "Apple", "Mango"];
        var x = document.getElementById("demo");
        x.innerHTML = Array.isArray(fruits);
      }
      <!DOCTYPE html>
      <html>
      <body>
      
      <p>Click the button to check if "fruits" is an array.</p>
      
      <button onclick="myFunction()">Try it</button>
      
      <p id="demo"></p>
      
      </body>
      </html>

      function myFunction() {
        var fruits = 'mango';
        var x = document.getElementById("demo");
        x.innerHTML = Array.isArray(fruits);
      }
      <!DOCTYPE html>
      <html>
      <body>
      
      <p>Click the button to check if "fruits" is an array.</p>
      
      <button onclick="myFunction()">Try it</button>
      
      <p id="demo"></p>
      
      </body>
      </html>

      【讨论】:

        猜你喜欢
        • 2017-01-30
        • 2017-03-02
        • 1970-01-01
        • 2011-10-19
        • 1970-01-01
        • 1970-01-01
        • 2013-03-22
        • 2015-04-14
        • 2011-03-01
        相关资源
        最近更新 更多