解析JSON响应并将值附加到div

时间:2017-02-01 08:34:47

标签: php jquery ajax

我在JSON.parse(response);中有这样的数据:

{
    "booking_trip": {
        "no_of_traveler": "2",
        "pack_stat_date": "02\/20\/2017",
        "pack_final_date": "02\/27\/2017",
        "package_details_id": "273",
        "promo_discount": "",
        "discount": ""
    },
    "price": "5000"
}

如何将这些值附加到特定的div?

1 个答案:

答案 0 :(得分:2)

解析后,您可以使用.Dot表示法来使用访问属性。或者如果你不喜欢.dot表示法,你可以使用如下。

示例版本

 var obj = JSON.parse(response);
    for(var prop in obj.booking_trip){

      var propvalue = obj.booking_trip[prop];
    $("div").append(propvalue);

    }

完整代码

 <body>
   <table>
    <thead>
      <tr>
       <td>Propery</td>
      <td>Value</td>
      </tr>

    </thead>
    <tbody>

    </tbody>
   </table>
   <script type="text/javascript">

  $(function(){

    var json = {
    "booking_trip": {
        "no_of_traveler": "2",
        "pack_stat_date": "02\/20\/2017",
        "pack_final_date": "02\/27\/2017",
        "package_details_id": "273",
        "promo_discount": "",
        "discount": ""
    },
    "price": "5000"


};

var $tbody = $("tbody");
for(var pro in  json.booking_trip ){
 var $row = $("<tr></tr>");
   $row.append($("<td>"+pro+"</td>"));
   $row.append($("<td>"+json.booking_trip[pro]+"</td>"));
   $tbody.append($row);
}

  })
</script>
  </body>