Jquery Json Array 响应未在 Div 中打印
Posted
技术标签:
【中文标题】Jquery Json Array 响应未在 Div 中打印【英文标题】:Jquery Json Array response not printing in Div 【发布时间】:2021-09-12 08:41:00 【问题描述】:我通过 AJAX 将我的订单 ID 发布到一个 php 页面,并且我收到了 json 响应。
我需要在我正在尝试的 sn-p 下方的跟踪订单页面中显示这一点,但我收到错误 TypeError: obj.map is not a function.
我尝试输入var htmlText = obj.response_data. map(function(o)
仍然出现错误。如何在我的 DIV 中打印 json 响应
trackorder.php
<div class="track-order-response">
</div>
$.ajax(
url: '<URL>/trackordercompute.php',
type: 'post',
data: order_id,
success: function( data )
var obj = $.parseJSON( data );
var htmlText = obj.map(function(o)
return `
<div class="div-conatiner">
<p class="p-name"> Transdate: $o.Transdate</p>
<p class="p-loc"> Transtime: $o.Transtime</p>
<p class="p-desc"> deliveredTo: $o.deliveredTo</p>
<p class="p-created"> Remarks: $o.Remarks</p>
<p class="p-uname"> Location: $o.Location</p>
</div>
`;
);
$('.track-order-response').html( htmlText );
,
error: function( jqXhr, textStatus, errorThrown )
console.log( errorThrown );
$('.track-order-response').html( errorThrown );
);
trackordercompute.php
我的 JSON 响应
echo '
"result":
"requested_data":
"AuthCode": "XXXX",
"OrderNumber": "INV374837"
,
"response_data": [
"Transdate": "11/02/2019",
"Transtime": "10:15",
"StatusCode": "POD",
"deliveredTo": "Rajendran",
"Remarks": "",
"Location": "Sharjah"
,
"Transdate": "11/02/2019",
"Transtime": "08:20",
"StatusCode": "OD",
"deliveredTo": "",
"Remarks": "OUR FOR DELIVERY",
"Location": "Dubai"
,
"Transdate": "10/02/2019",
"Transtime": "20:10",
"StatusCode": "AF",
"deliveredTo": "",
"Remarks": "ARIVED AT SERVICE CENTER",
"Location": "Dubai"
,
"Transdate": "10/02/2019",
"Transtime": "11:00",
"StatusCode": "C",
"deliveredTo": "",
"Remarks": "Airway Bill Check In",
"Location": "Dubai"
]
';
【问题讨论】:
因为map
用于数组,但返回的data
似乎是一个对象。你试过obj.response_data.map(...)
吗?
是的,我试过了。它不工作。
【参考方案1】:
有用的是 ForEach 而不是 map
$.ajax(
url: 'trackordercompute.php',
type: 'post',
data: order_id,
success: function( data )
var obj = $.parseJSON( data );
var htmlData="";
obj.result.response_data.forEach((o) =>
htmlData +=`
<div class="div-conatiner">
<p class="p-name"> Transdate: $o.Transdate</p>
<p class="p-loc"> Transtime: $o.Transtime</p>
<p class="p-desc"> deliveredTo: $o.deliveredTo</p>
<p class="p-created"> Remarks: $o.Remarks</p>
<p class="p-uname"> Location: $o.Location</p>
</div>
`;
);
$('.track-order-response').html( htmlData );
,
error: function( jqXhr, textStatus, errorThrown )
console.log( errorThrown );
$('.track-order-response').html( errorThrown );
);
【讨论】:
以上是关于Jquery Json Array 响应未在 Div 中打印的主要内容,如果未能解决你的问题,请参考以下文章