我有一个AJAX提交表单。我得到的字段值为null。
jQuery(\'#DownloadForm\').submit(ajaxSubmit);
function ajaxSubmit() {
var DownloadForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: aj_ajax_demo.ajax_url,
data : {
action : \'set_lead_cookie_and_mail\', // Note that this is part of the add_action() call.
nonce : aj_ajax_demo.aj_demo_nonce, // Note that \'aj_demo_nonce\' is from the wp_localize_script() call.
form_data : DownloadForm
},
success: function(response) {
console.log(response);
}
});
return false;
}
这就是我获取数据的方式。
add_action( \'wp_ajax_nopriv_set_lead_cookie_and_mail\', \'mail_and_cookie_function\' );
add_action( \'wp_ajax_set_lead_cookie_and_mail\', \'mail_and_cookie_function\' );
function mail_and_cookie_function() {
check_ajax_referer( \'aj-demo-nonce\', \'nonce\' ); // This function will die if nonce is not correct.
$name = sanitize_text_field($_POST["wpcf-lead-name"]);
$email = sanitize_text_field($_POST["wpcf-lead-email"]);
$number = sanitize_text_field($_POST["wpcf-lead-number"]);
$class = $_POST["wpcf-class"];
$category = sanitize_text_field($_POST["hidden_category"]);
if(!$_COOKIE[$category]) {
setcookie($category, "1", time()+2592000);
wp_send_json($class);
}
wp_die();
}
我的响应标头正确发送了所有数据。
我的响应为null。我希望得到所提交表格的价值。
最合适的回答,由SO网友:Bhanu 整理而成
所以我找到了问题的答案。使用parse_str($_POST[\'form_data\'], $form_data);
在我的函数中,允许我调用所有字段值$name = $form_data["wpcf-lead-name"];
现在,我的新函数如下所示。
function mail_and_cookie_function() {
check_ajax_referer( \'aj-demo-nonce\', \'nonce\' );
parse_str($_POST[\'form_data\'], $form_data); // This is the new added line
$name = $form_data["wpcf-lead-name"]; // This is how you call the field.
$email = $form_data[\'wpcf-lead-email\'];
$number = $form_data["wpcf-lead-number"];
$class = $form_data["wpcf-class"];
$category = $form_data["hidden_category"];
if(!$_COOKIE[$category]) {
setcookie($category, "1", time()+2592000);
wp_send_json("redirecting");
}
wp_die();
}