我试图通过wordpress admin ajax发送序列化数据,但我得到的是以下格式的输出,而不是序列化格式。
审阅者备注=已批准(&N);app\\U rej\\U posts=118059
Jquery Ajax Code Below
$.ajax({
type: \'POST\',
dataType: \'json\',
url: ajax_reviewer_object.ajaxurl,
data: {
\'action\': \'reviewer_action\', //calls wp_ajax_nopriv_ajaxlogin
\'post_data\': $(\'#approval_system\').serialize()
},
success: function(data){
$("#lrm_msg").html(data.message);
}
});
PHP Function Below:
function reviewer_action_callback(){
$ss = $_POST[\'post_data\'];
pre($ss);
}
add_action( \'init\', \'reviewer_action\' );
function reviewer_action() {
wp_enqueue_script(\'ajax-post-script\');
wp_localize_script( \'ajax-post-script\', \'ajax_reviewer_object\', array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
\'load_msg\' => plugins_url(\'lyca-draft-approval/assets/img/ajax-loader.gif\')
));
//add_action( \'wp_ajax_nopriv_ajax_post\', \'ajax_post\' );
add_action( \'wp_ajax_reviewer_action\', \'reviewer_action_callback\' );
}
SO网友:Tom J Nowell
与其依赖定制/自定义序列化和古老的管理AJAX,不如考虑使用JSON和REST API,例如:
add_action( \'rest_api_init\', function () {
register_rest_route( \'ramkumar/v1\', \'/test/\', array(
\'methods\' => \'POST\',
\'callback\' => \'ramkumar_rest_test\'
) );
} );
function ramkumar_rest_test( $request ) {
$reviewer_notes = $request[\'reviewer_notes\'];
$result = ....;
return $result; // gets sent to the browser as JSON, so return an object/array/etc
}
现在我们有了
yoursite.com/wp-json/ramkumar/v1/test
可以这样戳它:
jQuery.ajax({
url: "/wp-json/ramkumar/v1/test",
data: { review_note: "hello I\'m a reviewer" }
}).done(function( data ) {
// json decode data and do stuff with it
});
这还具有更易于调试、更易于使用等优点。REST API可以接受多个额外参数,告诉它如何验证、清理和验证请求。如果你犯了错误,它还会用通俗易懂的英语告诉你做错了什么