我关注此处的页面 - http://solislab.com/blog/5-tips-for-using-ajax-in-wordpress/#admin-ajax
所以我有一个简单的表格
<form role="form">
<div class="form-group">
<label class="">Name</label>
<input type="text" id="name" class="form-control" name="name" />
</div>
<div class="form-group">
<label class="">Email</label>
<input type="text" id="email" class="form-control" name="email" />
</div>
</form>
在functions.php
我有
// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . '/js/compiled/main.min.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );
function myajax_submit() {
// get the submitted parameters
$name = $_POST['name'];
$email = $_POST['email'];
// generate the response
$response = json_encode( array( 'success' => true ) );
// response output
header( "Content-Type: application/json" );
echo $response;
// IMPORTANT: don't forget to "exit"
exit;
}
我使用grunt连接我的js文件,然后将其缩小为/js/compiled/main.min.js
这个缩小的文件包含用于验证表单和帖子功能的js。
js
$atj(function(){
$atj('.js-training').click(function(e) {
//
e.preventDefault();
if(verfiyTrainingFields()) {
$atj.post(
MyAjax.ajaxurl,
{
action : 'myajax-submit',
firstName : $atj("#name").val(),
email : $atj("#email").val(),
},
function(response){
alert(response);
}
)
}
});
})
//Verfiy
function verfiyTrainingFields() {
var flag = true;
var name = $atj('#name');
var email = $atj('#email');
if(name.val().indexOf(' ') === -1 ){
name.parent().prepend('<p class="form-error">Please enter name, first space last</p>');
fadeOut();
flag = false;
}
if(!IsEmail(email.val())){
email.parent().prepend('<p class="form-error">Please enter valid email address</p>');
fadeOut();
flag = false;
}
return flag;
}
我在控制台中收到错误
Uncaught ReferenceError: MyAjax is not defined
更新
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_register_script('scripts',get_template_directory_uri() . '/js/compiled/main.min.js', array('jquery'),1 ,true);
wp_enqueue_script('scripts');
//
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . '/js/compiled/main.min.js', array( 'jquery' ),'', true );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));
}