【问题标题】:Pass variable to php script with AJAX使用 AJAX 将变量传递给 php 脚本
【发布时间】:2016-12-14 02:04:58
【问题描述】:

我不确定我是否了解 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 发送一些变量怎么办?

【问题讨论】:

  • data: {'checked': 'checked'}
  • checked 是一个变量..
  • 您在文档就绪时运行 AJAX,而不是使用 click 事件
  • 检查控制台中的任何错误。你有什么具体的错误吗?

标签: javascript php ajax wordpress woocommerce


【解决方案1】:

问题是您需要先序列化发布数据。

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

<input type = "checkbox" id = "billing_postcode" name = "billing_postcode">

JS 代码

$(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']);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 2012-11-15
    • 1970-01-01
    • 2014-04-23
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多