【发布时间】:2021-10-13 09:42:01
【问题描述】:
我正在尝试根据从下拉列表中选择的国家/地区使用 ajax 和 php 执行 onchange 事件。我的问题是响应为每个项目设置了数组中的最后一个价格,我想不出解决这个问题的方法。 到目前为止,这是我的代码:
$("#field-organization-country-iso").on('change', (e) => {
e.preventDefault();
e.stopPropagation();
const CountryIso = $('#field-organization-country-iso').val();
Request.get(`/myrequested_file`, {
data: { CountryIso },
})
.done((response) => {
for (let i = 0; i < response.data.itemPrice.length; i++) {
const price = response.data.itemPrice[i];
$('.checkout-table tr').find('.hide-if-odd-or-sub').eq(i).html(price);
}
});
});
还有 php 函数:
public function change_currencyIso(Request $request, $summaryService): JSONResponse
{
$countryIso = $request->query->get('CountryIso');
$response = new JSONResponse();
$orderSummary = $summaryService->Summary(Cart::getCurrentCart(), User::currentUserOrNull(), $countryIso, null, null);
$items = $orderSummary->getItems();
$currencies = new ISOCurrencies();
$numberFormatter = new NumberFormatter(Environ::getLocale(), NumberFormatter::CURRENCY);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, $currencies);
$prices = [];
foreach ($items as $item) {
$price = $moneyFormatter->format($item->getLocalPrice());
$prices[] = $price;
}
$response->setVar('itemPrice', $prices);
return $response;
}
$prices 返回包含商品价格的数组,但我知道响应会覆盖它。我可以遍历数组并将响应添加到每个价格吗? 我对“itemPrice”的回复仅返回现有价格之一。
{itemPrice: Array(2)}
itemPrice: Array(2)
0: "245,00 US$"
1: "32,90 US$"
length: 2
现在 itemPrice 返回数组,但仍将所有内容放在同一行。尝试了一个,但没有帮助。
【问题讨论】:
-
用
$prices[] = $price;代替$prices = [$price];?你可以阅读this article。