简体   繁体   中英

Populate HTML with JSON array in Javascript

This question has been asked a couple of time here, but I haven't seen any of the responses work for me.

I have this piece of code built with cakePHP which successfully returns the data in JSON format, but I haven't been able to insert this JSON data into HTML div using Javascript.

$('.book-click').click(function (e) {
    e.preventDefault();
    var getHotel = $(this).attr('hotel-id');

    $.ajax({
        type: "POST",
        url: "<?php echo $this->Html->URL(array('action' => 'postBook')); ?>",
        data: {
            hotel: getHotel
        },
        cache: false,
        dataTye: "json",
        success: function (JSONObject) {
            var myData = "";
            for (var key in JSONObject) {
                if (JSONObject.hasOwnProperty(key)) {
                    myData += JSONObject[key];
                }
            }
            /*console.log(myData);*/
            alert(myData[key]["hotelname"]); //Giving undifined in alert

        }
    });
});

And this is the JSON data I get when I log the data on browser console:

[
    {
        "id": "11",
        "hotelname": "Sheraton hotel",
        "hoteladdress": "Abule Ikeja",
        "state": "Lagos State",
        "lga": "Ikeja",
        "hotelphone": "65645545454",
        "hotelwebsite": "",
        "adminphone": "6565656565",
        "adminemail": "mail@hotel.com",
        "hotelemail": "",
        "facilities": ",,",
        "roomscategory": "Diplomatic",
        "standardrate": "150000",
        "leanrate": "",
        "aboutHotel": "",
        "requestStatus": "0",
        "createdOn": "1424360902",
        "updatedOn": "1424360902"
    }
]

How do I successfully, get this JSON data into HTML. Something like this:

$('#myDiv').html(myData[key]["hotelname"]);

I tried this, but it's just giving me Undefined .

Any help is appreciated.

Use $.each() to iterate:

success: function (JSONObject) {
    $.each(JSONObject, function(k,item){
       $('#myDiv').html(item.hotelname);
    });
}

 var json = [ { "id": "11", "hotelname": "Sheraton hotel", "hoteladdress": "Abule Ikeja", "state": "Lagos State", "lga": "Ikeja", "hotelphone": "65645545454", "hotelwebsite": "", "adminphone": "6565656565", "adminemail": "mail@hotel.com", "hotelemail": "", "facilities": ",,", "roomscategory": "Diplomatic", "standardrate": "150000", "leanrate": "", "aboutHotel": "", "requestStatus": "0", "createdOn": "1424360902", "updatedOn": "1424360902" } ] $.each(json, function(i, item){ $('body').append(item.hotelname); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 


As per your error, it seems that you either you don't have a valid json or that is a json string. So before loopin you have to parse it:

success: function (JSONObject) {
    var data = $.parseJSON(JSONObject); // parse it
    $.each(data, function(k,item){
       $('#myDiv').html(item.hotelname);
    });
}
var myData = "";
for (var key in JSONObject) {
   if (JSONObject.hasOwnProperty(key)) {
       myData += JSONObject[key];
   }
}

myData here is simply just a string . Hence the call myData[key]["hotelname"] will return undefined, because you're trying to access something that does not exist.

Why not just use the result as-is from the Ajax call?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM