2016-08-08 70 views
1

我不确定我了解ajax如何工作,即使我阅读了大量的内容。 我想,如果一个按钮被点击,无需加载页面运行下面的PHP:将变量传递给使用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怎么办?

+2

'data:{'checked':'checked'}' – Saurabh

+1

checked是一个变量.. – Avishay28

+0

您正在文件运行时运行AJAX,而不是使用'click'事件 – Saurabh

回答

3

问题是你需要先将帖子数据序列化为

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!'), 
    }) 
}); 

您将获得在服务器端和enter code here在后数组值php脚本

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