jQuery,遍历AJAX JSON响应并追加到元素ID数组中

问题描述 投票:0回答:1

我发现了一些类似的问题,但并不是我真正需要的。我正在使用AJAX来获取物业可用性的实时状态。我正在根据需要获得响应,并且可以在控制台日志中看到响应。我不确定该怎么做,就是遍历JSON响应并将信息附加到现有元素ID上以显示可用性。

JSON响应设置如下:[{status: AVAILABLE, category: 21}, {status: SOLDOUT, category: 19}]

$.ajax({
  url: bta_obj.ajaxurl,
    data: {
      'action': 'get_checkfront_items',
      'arrive' : arrive,
      'depart' : depart,
      'categories' : categories,
    },
    type: "POST",
    success:function(data) {
    var json = $.parseJSON(data);
    $(json).each(function(i,val){
      $.each(val,function(k,v){
        // here is where the magic needs to happen      
      });
    });
   },
   error: function(errorThrown){
     alert('well darn it....');
   }
 });

存在与类别ID匹配的div ID。因此,我首先需要确定类别ID是否与div ID相匹配,然后将状态附加到该div ID。希望有道理。

更新

对于那些在示例JSON响应中看不到过去简单错字的人,我添加了急需的括号。...

jquery ajax
1个回答
1
投票

jQuery提供the ID selector以通过其ID获得DOM元素,并提供text方法以更改DOM元素innerText。

$(json).each(function(i,val){
  $('#'+val.category).text(val.status);
});
© www.soinside.com 2019 - 2024. All rights reserved.