小编典典

使用来自Ajax响应的JSON数据数组?

ajax

是否可以在PHP中处理来自AJAX请求的响应?我不是一个真正的JS开发人员,所以我正在用这个开发人员。

我有点黑了:

      var base_url = 'http://dev.local/westview/public';

  $('select.child_id').change(function() {

var child_id = $('#child_id');
var dataString = 'child_id=' + child_id;

$.ajax({
  type: "POST",
  url: base_url + "/finance/payment-history",
  data: dataString,
  dataType: 'html',
  success: function(html) { 
    alert(html);
  },

});
return false;

});

该功能似乎可以正常运行,它会向我发出有关正确数据的警报。

{"payments":[{"id":"19","child_id":"21","club":"Breakfast Club","term":"Half Term 3","amount":"15.00","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:32","updated_at":"2015-02-11 12:16:32","starting_debt":"0","debt_start_date":"2015-01-05"},{"id":"20","child_id":"21","club":"After School Club","term":"Half Term 3","amount":"11.50","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:49","updated_at":"2015-02-11 12:16:49","starting_debt":"0","debt_start_date":"2015-01-05"}]}

我需要能够将此输出给用户,以便可读。我发现很多指南都描述了替换数据,但就目前而言,直到选择child_id之前,没有数据。.然后我希望它以可读的方式显示上述数据。

我不知道如何开始使用视图文件(php)中的数据。

谢谢

[EDIT]已使用工作代码更新:

var base_url =’
http://dev.local/westview/public ‘;

$('select.child_id').change(function() {

  var response = "";
  var child_id = $('#child_id').val();
  var dataString = 'child_id=' + child_id;

  $.ajax({
    type: "POST",
    url: base_url + "/finance/payment-history",
    data: dataString,
    success: function(response) {

      var json_obj = $.parseJSON(response);

      var output = "<ul>";

      for (i=0; i < json_obj.payments.length; i++)
      {
        var payment = json_obj.payments[i];
        var date = moment(payment.pdate).format('Do MMM YYYY');
        output += "<li>&pound;" + payment.amount + " - " + date + " (" + payment.club + ")</li>";
      }

      output += "</ul>";

      $('.history-section').html(output);

    },
    dataType: "html"
  });
});

阅读 235

收藏
2020-07-26

共1个答案

小编典典

这样吧

var data = $.parseJSON("your_json");
var output= "<ul>";

for (i=0; i < data.payments.length; i++){
    output += "<li>" + data.payments[i].id + ", " + data.payments[i].child_id + "</li>";
}

output += "</ul>";
2020-07-26