• $.each遍历json对象


    var json = [
        {"id":"1","tagName":"apple"},
        {"id":"2","tagName":"orange"},
        {"id":"3","tagName":"banana"},
        {"id":"4","tagName":"watermelon"},
        {"id":"5","tagName":"pineapple"}
    ];
     
    $.each(json, function(idx, obj) {
        alert(obj.tagName);
    });
    技术分享

    上面的代码片断工作正常,提示 “apple”, “orange” … 等,如预期一样。

    问题: JSON 字符串

    下面的例子中,声明了一个JSON字符串(随附单或双引号)直接地。

    技术分享
    var json = ‘[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
    {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
    {"id":"5","tagName":"pineapple"}]‘;
     
    $.each(json, function(idx, obj) {
        alert(obj.tagName);
    });
    技术分享

    在Chrome中,它显示在控制台下面的错误:

    Uncaught TypeError: Cannot use ‘in‘ operator to search for ‘156‘ 
    in [{"id":"1","tagName":"apple"}...

    解决方案:JSON字符串转换为JavaScript对象。
    要修复它,通过标准JSON.parse()或jQuery 的 $.parseJSON 将其转换为JavaScript对象。

    技术分享
    var json = ‘[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
    {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
    {"id":"5","tagName":"pineapple"}]‘;
     
    $.each(JSON.parse(json), function(idx, obj) {
        alert(obj.tagName);
    });
     
    //or 
     
    $.each($.parseJSON(json), function(idx, obj) {
        alert(obj.tagName);
    });
    技术分享
  • 相关阅读:
    free
    Lynyrd Skynyrd
    Tree 园丁的烦恼
    On Changing Tree
    Path Queries
    Java开发中的23种设计模式详解(转)
    cas单点登录实现
    Java内存溢出详解
    java多线程并发
    java代码实现图片处理功能。对图片质量进行压缩。
  • 原文地址:https://www.cnblogs.com/huangwentian/p/7077933.html
Copyright © 2020-2023  润新知