Reputation: 585
I'm very new to how to load JSON text with JavaScript or JQuery. I'm new to JSON overall. So I have PHP giving me some some JSON text of images I have store in my server like this:
[
[{
"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"
}]
]
I want to be able to load this JSON text with JQuery and I managed to put together this function to load the script from a text area
input field. This is my 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>
This is my JQuery script.
$("#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);
});
But it doesn't work for me. Thank you in advanced for your help!
Upvotes: 0
Views: 79
Reputation: 5316
<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>
Output is two images into DIV
with imgResult
ID.
Upvotes: 1