2016-02-29 150 views
0

我对如何使用JavaScript或JQuery加载JSON文本非常陌生。我是JSON的新手。所以我PHP给我,我有存储图像的某些部分JSON文字在我的服务器这样的:JQuery不加载JSON文本

[ 
    [{ 
     "name": "11_by_Shelest.jpg", 
     "imgPath": "img/14567045410.jpg", 
     "Img_ID": "62", 
     "Date_Posted": "2016-02-28 17:09:01" 
    }, { 
     "name": "1227.jpg", 
     "imgPath": "img/14566992060.jpg", 
     "Img_ID": "39", 
     "Date_Posted": "2016-02-28 15:40:06" 
    }] 
] 

我希望能够加载使用jQuery这个JSON文本,我设法拼凑这个函数来加载来自text area输入字段的脚本。这是我的HTML:

<textarea name="jsonText" rows="5" class="form-control" id="jsonText"></textarea> //JSON is added here and grabbed with JQuery 
<button type="button" class="btn btn-success btn-lg" name="loadImages" id="loadImages">Load Images </button> 

这是我的JQuery脚本。

$("#loadImages").click(function(e){ 
    var jsonText = $('#jsonText').val(); 
    var images = JSON.parse(jsonText); 

    //console.log(images); 

     var imgList= []; 
     $.each(images[0], function (name, imgPath) { 
      console.log(name + " " + imgPath); 
      imgList += '<img src= "' + imgPath + '" alt="' + name + '">'; 
     }); 
     $('#imgResult').append(imgList); 

}); 

但它不适用于我。先进的谢谢您的帮助!

+0

什么是图像的内容?它应该是JSON文件的路径,是吗? – Cruiser

+1

如果您的JSON字符串位于textarea中,则不需要使用'$ .getJSON'。事实上,这很可能会导致语法错误。您发布的JSON样本也无效。 –

+0

@Cruiser图像被解析后是JSON对象。 –

回答

1
<textarea name="jsonText" rows="5" class="form-control" id="jsonText"> 
     [ 
      [{ 
       "name": "11_by_Shelest.jpg", 
       "imgPath": "img/14567045410.jpg", 
       "Img_ID": "62", 
       "Date_Posted": "2016-02-28 17:09:01" 
      }, { 
       "name": "1227.jpg", 
       "imgPath": "img/14566992060.jpg", 
       "Img_ID": "39", 
       "Date_Posted": "2016-02-28 15:40:06" 
      }] 
     ] 
    </textarea> 
    <button type="button" class="btn btn-success btn-lg" name="loadImages" id="loadImages">Load Images </button> 
    <div id="imgResult"></div> 
    <script> 
     $("#loadImages").click(function(e){ 
      var jsonText = $('#jsonText').val(); 
      var images = JSON.parse(jsonText); 
      var imgList = ''; 
      $.each(images[0], function (id, imgArray) { 
       console.log(imgArray); 
       imgList += '<img src= "' + imgArray.imgPath + '" alt="' + imgArray.name + '">'; 
      }); 
      $('#imgResult').append(imgList); 
     }); 
    </script> 

输出是DIV的两幅图像,其中imgResult ID。

JSFiddle Demo

+0

嗨,谢谢你的帮助,这就是'0'这个页面追加的内容'所以它看起来并没有传递对象的值,而是传递了对象本身的值 –

+0

检查JSFiddle演示:https:// jsfiddle.net/y6d7L0L4/ – mitkosoft

+0

老兄!它疯了!我复制了你的代码并试了一下,它不适合我!这是无稽之谈! –