当前位置: 动力学知识库 > 问答 > 编程问答 >

html - Iterate through json on webpage ( jquery)

问题描述:

I have a form I collect data from and then I insert them in url string,

thus I get url like http://terminal2.expedia.com/x/mhotels/search?city=hersbruck&checkInDate=2016-12-01&checkOutDate=2016-12-03&room1=2&apikey=RZjKNligNc0QZJvV9HP1nbFm1jrghgLK

This url returns valid json directly on the page

{

numberOfRoomsRequested: 1,

filterUnavailableHotelsRequested: false,

totalHotelCount: 94,

availableHotelCount: 60,

searchRegionId: "6124915",

searchRegionCity: "Hersbruck",

deepLinkUrl: "https://www.expedia.com/Hersbruck-Hotels.d6124915.Travel-Guide-Hotels",

hotelList: [

{

sortIndex: "0",

hotelId: "2813073",

name: "Md Hotel Restaurant Bauer",

localizedName: "Md Hotel Restaurant Bauer",

nonLocalizedName: "Md Hotel Restaurant Bauer",

address: "Martin Luther Str 16",

city: "Hersbruck",

........

and I try to get some data from it to create table, with such code:

$(document).ready(function(){

$('#submit-btn').click(function(s) {

$("form").submit(function (event) {

var place = (document.querySelectorAll('#place')[0].value);

var check_in = (document.querySelectorAll('#check-in')[0].value);

var check_out = (document.querySelectorAll('#check-out')[0].value);

var api_key = "RZjKNligNc0QZJvV9HP1nbFm1jrghgLK";

var url = "http://terminal2.expedia.com/x/mhotels/search?city=" + place + "&checkInDate=" + check_in + "&checkOutDate=" + check_out + "&room1=2&apikey=" + api_key + ""

$.getJSON(url, function (data){

var div = $("#result");

var table = '<table><tbody>';

for (i in data) {

var tr = '<tr><td>'+data[i].name+'</td><td>'+data[i].city+'</td></tr>'

table = table+tr;

}

table = table + "</tbody></table>";

div.html(table);

});

event.preventDefault();

});

});

});

but I receive table with undefined

What I do wrong, please point me out.

网友答案:

I'm guessing you want to display the hotels from the hotelList returned by the API. Then wouldn't your loop be more like:

for (hotel in data.hotelList) {
  var tr = '<tr><td>'+ hotel.name+'</td><td>'+ hotel.city+'</td></tr>'
  table = table+tr;
}

I changed i for hotel for clarity sake.

But since I can't see the whole JSON, I don't know if my guess is right.

分享给朋友:
您可能感兴趣的文章:
随机阅读: