【问题标题】:Set different prices according to country with response根据国家/地区设置不同的价格并做出响应
【发布时间】: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

标签: php jquery ajax


【解决方案1】:

您应该添加有关 html 结构的更多详细信息,但是我想您有一个表格,其中每个项目都有一行,并且带有价格的单元格具有“hide-if-odd-or-sub”类。此外,表行与服务器返回的价格顺序相同。因此,您必须将每个价格分配给对应的表行:

foreach (var i in response.data.itemPrice) {
    var price = response.data.itemPrice[i];
    $('.checkout-table tr').eq(i).find('.hide-if-odd-or-sub').html(price);
}

这并不可靠,因为如果用户在另一个浏览器的选项卡中更改购物车中的项目并返回上一个选项卡并更新国家/地区,那么服务器返回的价格将与表中的项目不对应, 但是它应该在正常使用下工作。

【讨论】:

  • 几乎完美无缺。做了一些小改动!更新了我的代码示例。也许它也可以帮助其他人。谢谢!!
猜你喜欢
  • 1970-01-01
  • 2013-03-19
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
相关资源
最近更新 更多