如何使用javascript jquery在html页面中显示json(数组)响应

时间:2014-05-21 06:35:14

标签: javascript jquery html json

我有一些json响应,其中包含数组格式的数据。我必须在html page中逐个显示该数据。在我的html页面中,我为merchantname,productname和remove button添加了一些div元素。和json数据contanins数组相同的产品名称,商家名称,删除特定商家的按钮。现在,当我在页面中显示数据时,它显示了产品列表后商家的所有名称。意思是它就像 商家名称:abc MERCHANTNAME:XYZ

产品名:A1 产品名称:A2 删除商家1的按钮 删除商家2的按钮 但我想显示这样的数据 MERCHANTNAME:ABC 产品名称:A1 删除merchnant1的按钮 MERCHANTNAME:XYZ 产品名称:A2 删除merchnant2的按钮  这是代码

$("#merchantname").append("<font color='green'>"+(responseObj.merchants.merchantname[i])+"</font>"+"\n");
    $("#productname").append(responseObj.merchants.productname[i]+"\n");

    $("#remove").append("<input type='button' value='remove' onClick='remove(needID)'>"+"</input>"+"\n");

1 个答案:

答案 0 :(得分:0)

根据我对你的问题的理解,我写了一小段代码,可以帮助回答这个问题。

我会尝试回答你的任何问题。

//Create the dom from the json response
$.each(responseObj.merchants,function(index){
    record=$('<div/>',{'class':'record'});
    merchantname=$('<span/>',{'class':'merchant'});
    merchantname.text(responseObj.merchants[index].merchantname);

    productname=$('<span/>',{'class':'product'});
    productname.text(responseObj.merchants[index].productname);

    remove=$('<input/>',{'class':'remove','val':'Remove','type':'button'});

    record.append(merchantname).append(productname).append(remove);

    $('#view').append(record);
});

// Handler for the remove button
$(document).on('click','.remove',function(){
// Statement to remove record
    $(this).closest('.record').remove();
});

FIDDLE