通过AJAX将变量传递给php脚本

Pass variable to php script with AJAX

本文关键字:php 脚本 AJAX 变量 通过      更新时间:2023-09-26

我不确定我理解ajax是如何工作的,尽管我读了很多关于它的东西。我想运行以下php,如果一个按钮被点击,而不加载页面:

unset($checkout_fields['billing']['billing_postcode']);

所以我输入如下:

jQuery(document).ready(function($) {
    $('.keep-buying-wrapper').click(function(){
        $.ajax({
            url: "url-to-the-script.php",
            method: "POST",
            data: {'checked': checked},
            success: alert('success!'),
        });
    });
});

在我的php脚本中:

if( $_POST['checked'] == 'checked' ){
        unset($checkout_fields['billing']['billing_postcode']);
}

然而什么也没发生。即使弹出成功警报,POST['checked']仍为空。

是ajax应该触发php脚本?
如果我想发送一些变量到functions.php呢?

问题是您需要先序列化post数据

HTML代码(复选框id和名称为"billing_postcode"):

<input type = "checkbox" id = "billing_postcode" name = "billing_postcode">
<<p> JS代码/strong>
$(document).on('click', '#billing_postcode', function (event) {
    var data = $("#billing_postcode").serializeArray();
    $.ajax({
        url: "url-to-the-script.php",
        method: "POST",
        data: data,
        success: alert('success!'),
    })
});

您将在服务器端获得post数组中的值,并在php脚本:

中获得enter code here
if($_POST['billing_postcode'])
    unset($checkout_fields['billing']['billing_postcode']);