简体   繁体   English

使用Javascript中的JSON数组填充HTML

[英]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. 我已经用CakePHP构建了这段代码,该代码成功地以JSON格式返回了数据,但是我无法使用Javascript将该JSON数据插入HTML div。

$('.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: 这是我在浏览器控制台上记录数据时获得的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"
    }
]

How do I successfully, get this JSON data into HTML. 我如何成功地将JSON数据转换为HTML。 Something like this: 像这样:

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

I tried this, but it's just giving me Undefined . 我试过了,但这只是给我Undefined

Any help is appreciated. 任何帮助表示赞赏。

Use $.each() to iterate: 使用$.each()进行迭代:

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. 根据您的错误,似乎您没有有效的json或json字符串。 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 . myData只是一个string Hence the call myData[key]["hotelname"] will return undefined, because you're trying to access something that does not exist. 因此,调用myData[key]["hotelname"]将返回undefined,因为您正在尝试访问不存在的内容。

Why not just use the result as-is from the Ajax call? 为什么不按原样使用Ajax调用中的结果?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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