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>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM