javascript 在jQuery blade文件中使用php larval helper函数

hmae6n7t  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(120)

我在laravel helper函数中创建了一个函数来将基础货币转换为IP货币,当页面重新加载时它正在工作,但在产品属性中,当我们选择选项价格时,我如何在jQuery中使用laravel helper函数。

// This function is to change the base price to ip currency price.
function convertBaseCurrencyToIp($base_price){
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    $arr_ip = geoip()->getLocation($ipaddress);
    $base_currency = 'INR';
    $currency_of_ip = $arr_ip->currency;
    $currency_conversion = Currency::convert()->from($base_currency)->to($currency_of_ip)->amount($base_price)->round(2)->get();

    return $currency_conversion;
}

这是jQuery代码

$(document).on("click",".clear-attributes",function (){
        $(".checkbox").removeAttr("checked");
        $("#price").text(site_currency_symbol + parseFloat($("#price").data("main-price")).toFixed(2));

        let old_image = $("#product-image").val();
        $(".attribute_img").attr("src",old_image);

        showAndHideClearButton($(".checkbox:checked").length);
    })

    $(document).on("click",".checkbox",function (){
        showAndHideClearButton($(".checkbox:checked").length);
    });
djp7away

djp7away1#

您可以将其作为值传递给视图。

$conversion = convertBaseCurrencyToIp($base_price)

return view('your-view', ['conversion' => $conversion]);

然后在刀片文件中引用该值。

<script>
const conversion = '{{ $conversion }}';
...
</script>

但是如果你需要一些更动态的东西(javascript对页面上的东西做出React,然后显示一个值),那么你可能需要创建一个端点并向它发出请求。

Route::get('conversion-endpoint', ConversionController::class);
class ConversionController extends Controller
{
    public function __invoke(Request $request)
    {
        return response()->json([
            'data' => [
                'value' => convertBaseCurrencyToIp($request->base_price),
            ]
        ], 200);
    }
}
// js
$(document).on("click",".clear-attributes",function (){
    ...
    $.ajax('/conversion-endpoint').done(function (data) {
        const converted = data.value; // or data.data.value, I can't remember if jquery adds a wrapper or not
        ....
    })

相关问题