我需要将js变量推入php变量。AJAX url是通过wp\\u localize\\u脚本设置的,但它返回错误400错误请求。功能。php看起来像
wp_localize_script( \'script-js\', \'compareids_ajax\', array( \'ajax_url\' => admin_url(\'admin-ajax.php\')) );
自定义。js公司
var compareIDs = $(".table td input:checkbox:checked").map(function(){
return $(this).val();
}).get(); // <----
$(\'.selected\').text(compareIDs);
console.log(compareIDs);
$.ajax({
type: "POST",
url: compareids_ajax.ajax_url,
data: \'{ compareIDs : compareIDs }\',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function (errormessage) {
}
});
和我的筛选页面。php有
<?php
$compareIDs = array( $_POST[\'compareIDs\'] );
$args02 = array( \'post_type\' => \'custom\',
\'post__in\' => $compareIDs );
$loop02 = new WP_Query( $args02 );
while ( $loop02->have_posts() ) : $loop02->the_post();
?>
最合适的回答,由SO网友:Bikash Waiba 整理而成
首先,您需要将函数名作为附加数据发送为
$.ajax({
type: "POST",
url: compareids_ajax.ajax_url,
data: { // Data object
compareIDs : compareIDs,
action: \'your_ajax_function\' // This is required to let WordPress know which function to invoke
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log( msg );
},
error: function (errormessage) {
console.log( errormessage );
}
});
在php文件中
add_action(\'wp_ajax_nopriv_your_ajax_function\',\'your_ajax_function\'); // Ajax Function should be hooked like this for unauthenticated users
add_action(\'wp_ajax_your_ajax_function\',\'your_ajax_function\'); //
function your_ajax_function(){
$comparedIds = $_POST[\'compareIDs\']; // Your data is now available in $_POST
// Do your stuff here
die(); // At the end
}
请参见
wp_ajax_(action)