gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:08:25 24 4
gpt4 key购买 nike

是否可以在 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 之前没有数据。然后我希望它以可读的方式显示上述数据。

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

谢谢

[编辑]更新了工作代码:

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"
});
});

最佳答案

这样做。

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>";

关于javascript - 使用来自 Ajax 响应的 JSON 数据数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28985363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com