jquery each报 Uncaught TypeError: Cannot use 'in' operator to search for错误

用$.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>
posted @ 2020-01-11 19:50  白小白学IT  阅读(1180)  评论(0)    收藏  举报