我尝试用ajax运行wp表单,但控制台返回wordpress admin ajax。php 400错误请求。
jQuery(function ($) {
$(document).ready(function () {
jQuery(\'#form_add_to_cart\').on(\'submit\', function () {
jQuery.ajax({
url: \'https://domain.com/wp-admin/admin-ajax.php\',
method: \'post\',
contentType : \'application/json; charset=utf-8\',
data: $("#form_add_to_cart").serializeArray(),
success: function (response) {
alert(response);
},
fail: function (err) {
alert("There was an error: " + err);
}
});
return false;
});
});
});
这是我的功能。php文件:add_action(\'wp_ajax_send_form\', \'send_form\'); // This is for authenticated users
add_action(\'wp_ajax_nopriv_send_form\', \'send_form\'); // This is for unauthenticated users.
function send_form(){
if (isset($_POST[\'send_form\'])){
echo\'ok\';
}
else{
echo \'bad\';
}
}
和我的表格: <form name="form_add_to_cart" method="POST" class="form_product" id="form_add_to_cart" action="">
<input hidden="hidden" name="action" id="add_product_to_cart"
value="send_form">
<input class="btn btn-primary" type="submit"
name="add_to_cart-<?php echo $product_id; ?>" id="add_to_cart"
value="Dodaj">
所有形式:https://pastebin.com/YJXTjGjJ工作:
jQuery(function ($) {
$(document).ready(function () {
jQuery(\'#form_add_to_cart\').on(\'submit\', function () {
jQuery.ajax({
url: \'https://domain.com/wp-admin/admin-ajax.php\',
method: \'post\',
data: $("#form_add_to_cart").serializeArray(),
success: function (response) {
alert(response);
},
fail: function (err) {
alert("There was an error: " + err);
}
});
return false;
});
});
});