【问题标题】:how to show json (array)response in html page using javascript jquery如何使用javascript jquery在html页面中显示json(数组)响应
【发布时间】:2014-05-21 15:03:00
【问题描述】:

我有一些 json 响应,其中包含数组格式的数据。我必须在 html 页面中一一显示该数据。在我的 html 页面中,我为商家名称、产品名称和删除按钮添加了一些 div 元素。和 json 数据包含数组相同的产品名称,商家名称,删除特定商家的按钮。现在,当我在页面中显示数据时,它会在该产品列表之后向我显示商家的所有名称。意味着它就像 商户名称:abc 商户名:xyz

产品名称:a1 产品名称:a2 删除商家 1 的按钮 删除商家 2 的按钮 但我想像这样显示这些数据 商户名称:abc 产品名称:a1 删除 Merchant1 的按钮 商户名称:xyz 产品名称:a2 删除 Merchant2 的按钮 这是代码

$("#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");

【问题讨论】:

  • 使用 jsrender 或简单地迭代 json 数组以附加到您的页面中..

标签: javascript jquery html json


【解决方案1】:

根据我对您问题的理解,我编写了一小段代码,可能有助于回答问题。

我会尽力回答你的任何问题。

//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

【讨论】:

  • 看到这是 json "needs":{"customerNeeds":[{"needTitle":"Need a Mobile","needDescription":"Android","fromCustomer":"xyz"," needDate":"2013-12-20T07:39:39Z","needID":4,"needStatus":"pending"} ]} 现在我想打印 needtitle ,我像 $.each(response.needs, function (i, needs) { alert(needs.customerNeeds.needTitle); });但它没有显示任何东西。纠正我在这里做错了什么。
  • 谢谢你。但是请看这个我试过了,但我想要一个一个的数据意味着需要一辆自行车,之后它需要 id...不是所有都需要毕竟需要 id..jsfiddle.net/ardeezstyle/9c2Tn
  • @user3415421 能否请您对上一条评论更清楚一点?恐怕我无法理解。
  • 是的,当然..从我尝试过的你的链接,我得到了正确的数据,但出于设计目的,我希望数据应该像第一个需要的所有信息一样显示,然后是第二个需要的所有信息一个接一个。 .意思是假设我有需要标题和需要日期。然后我希望数据应该显示为第一个需要ID,它的需要日期然后第二个需要标题,第二个需要日期,但我得到的是第一个需要标题,第二个需要标题,第一个需要ID,第二个需要我不想要的 id。我也知道错误,因为我将它附加到 div 这就是为什么它会这样显示。但是如果你有任何其他想法。那么请告诉我。
  • 哦,我现在明白了。我已经为你重新编写了代码。实际上,所有的记录 div 都应该附加到具有 id 视图的同一个 div 中。由于您要附加到两个不同的 div,因此它不会如您所愿。请在这里找到小提琴jsfiddle.net/ardeezstyle/9c2Tn/4
猜你喜欢
  • 2020-04-20
  • 1970-01-01
  • 2019-12-28
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2018-04-02
相关资源
最近更新 更多