我相信您正在使用ajax引用process\\u表单。php。然而,访问任何ajax的正确方法是通过wp-admin/admin-ajax.php.
从中提取所有代码process_form.php 到函数(可以添加到主插件文件):
function my_process_form() {
//...code from process_form.php
if ( ! $error ) { //your error boolean
return wp_json_success(); //recommend for return an success as JSON
} else {
return wp_json_error(); //recommend for return an error as JSON
}
}
然后,向ajax操作添加一个挂钩,如下所示:
//You can choose one of those or leave both:
add_action( \'wp_ajax_my_process_form\', \'my_process_form\' ); //Only logged users
add_action( \'wp_ajax_nopriv_my_process_form\', \'my_process_form\' ); //Not logged users
在Javascript中,必须调用url
wp-admin/admin-ajax.php 在本例中,使用钩住的参数
my_proccess_form:
PHP调用JS并发送admin-ajax.php URL:
wp_enqueue_script( \'my-custom-script\', plugins_url( \'/js/my_custom.js\', __FILE__ ), array(\'jquery\') );
wp_localize_script(
\'my-custom-script\', //JS referenced above
\'ajax_object\', //Javascript Object
array(
\'ajax_url\' => admin_url( \'admin-ajax.php\' ) //Same as wp-admin/admin.ajax.php
)
);
我将向您发送一个使用jQuery进行AJAX请求的示例:
jQuery.ajax({
type : "post",
dataType : "json", //Example only
url : ajax_object.ajax_url, //From wp_localize_script
data : { //can use jQuery.serialize() as well
action: "my_process_form", //used on wp_ajax_(action) and wp_ajax_nopriv_(action)
post_id : 1, //Dummy id, more parameters, use comma
nonce: nonce //Read https://codex.wordpress.org/Function_Reference/wp_create_nonce
},
success: function( response ) {
if( response.success ) {
//Success JS Process
} else {
alert("Error");
console.log( response );
}
}
});
参考文献
https://codex.wordpress.org/AJAX_in_Plugins https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action) https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action) https://codex.wordpress.org/Function_Reference/wp_localize_script
----更新----
如果您喜欢在没有AJAX的情况下使用$\\u POST,那么可以使用挂钩admin_post_(action)
HTML示例:
<form action="<?php echo admin_url(\'admin-post.php\'); ?>" method="post">
<input type="hidden" name="action" value="my_process_form">
<input type="text" name="name">
<input type="email" name="email">
<input type="submit" value="Submit">
</form>
PHP示例:
add_action( \'admin_post_my_process_form\', \'my_process_form\' );
function my_process_form() {
// The process_form.php code here
}