我使用http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/作为指南来创建一个表单供用户填写信息,然后创建一个帖子在自定义帖子类型中。当我收到一长串警报时,我总是从服务器得到“0”的响应。有什么帮助吗?
我的插件文件php:
function ajaxurl() {
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url( 'admin-ajax.php' ),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
'postCommentNonce' => wp_create_nonce( 'myajax-post-comment-nonce' ),
)
);
}
add_action('wp_head', 'ajaxurl');
// if both logged in and not logged in users can send this AJAX request,
// add both of these actions, otherwise add only the appropriate one
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );
function myajax_submit() {
$nonce = $_POST['postCommentNonce'];
// check to see if the submitted nonce matches with the
// generated nonce we created earlier
if ( ! wp_verify_nonce( $nonce, 'myajax-post-comment-nonce' ) )
die ( 'Busted!');
// get the submitted parameters
$postID = $_POST['postID'];
if ( isset($_post['post_ID']) ) {
};
//Create Post from post data
$newpost = array(
'post_title' => $_POST['title'],
'post_author' => $_POST['author'],
'post_type' => 'assets',
'post_content' => $_POST['description'],
'post_category' => $_POST['category']
);
//Actually Create the post
$post_id = wp_insert_post($newpost);
//now that we have an ID we can add the post meta
update_post_meta($post_id ,'key', $_POST['key']);
update_post_meta($post_id ,'assetname', $_POST['assetname']);
update_post_meta($post_id ,'assetadd1', $_POST['assetadd1']);
update_post_meta($post_id ,'assetadd2', $_POST['assetadd2']);
update_post_meta($post_id ,'assetcity', $_POST['assetcity']);
update_post_meta($post_id ,'assetstate', $_POST['assetstate']);
update_post_meta($post_id ,'assetzipcode', $_POST['assetzipcode']);
update_post_meta($post_id ,'assetlocation', $_POST['assetlocation']);
// generate the response
$response = json_encode( array( 'success' => true ) );
// response output
header( "Content-Type: application/json" );
echo $response;
die();
// IMPORTANT: don't forget to "exit"
exit;
}
我的 jQuery: 出于某种原因,除非我添加 $(document).ready 片段,否则 jquery 不会触发
$(document).ready(function () {
jQuery('#myForm').submit(function() {
data = $(this).serialize();
data = data + "&postCommentNonce=" + MyAjax.postCommentNonce + "&action=myajax_submit";
alert( data );
到目前为止,一切正常。我从表单输入字段中得到一长串输入
jQuery.post(
MyAjax.ajaxurl,
data,
function( response ) {
alert( response );
}
);
return false;
});
});
毕竟,我每次仍然只能从服务器收到“0”的响应。对此的任何帮助将不胜感激。