用$.each()来遍历后台传过来的json数据
用$.each()来遍历后台传过来的json数据。直接遍历传过来的数据时就产生 Uncaught TypeError: Cannot use ‘in‘ operator to search for 这个error。
原因是:因为我们后台传过来的是json数据,,但我们$.each()遍历的数据是要javascript东西;所以要把它转给javascript东西。可以使用 JSON.parse() || $.parseJSON() 这个两个要领来转换。
错误代码:
<script> $(document).ready(function(){ $("#searchbtn").click(function(){ $("#searchres").html(""); $.get("test.php",{searchkeyword:$("#keyword").val()}) .done(function(data){ var html=‘‘; $.each(data,function(i,v){ html += v.number; }); $("#searchres").append(html); }) .fail(function(xhr){ console.log(xhr.status); }) }); }); </script>
正确代码:
<script> $(document).ready(function(){ $("#searchbtn").click(function(){ $("#searchres").html(""); $.get("test.php",{searchkeyword:$("#keyword").val()}) .done(function(data){ var html=‘‘; $.each(JSON.parse(data),function(i,v){ html += v.number; }); $("#searchres").append(html); }) .fail(function(xhr){ console.log(xhr.status); }) }); }); </script>
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31785.html