我一直在关注多个关于此的教程(包括 Wordpress 自己的教程),它让我有点疯狂。
我试图让 AJAX 在 Wordpress 的前端工作,但它根本没有做任何事情,我知道该功能可以工作,因为我已经独立测试过这个功能,您的输入将非常感谢。非常感谢。
functions.php中的代码
function call_ajax()
{
//assuming this is in a theme?
wp_enqueue_script( 'ajax_car_models', get_template_directory_uri() . '/js/ajax_car_models.js', array( 'jquery' ), null, true);
//loacalize the script using the same handle it was registered / enqueued with
wp_localize_script( 'ajax_car_models', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
//make a call to call_ajax at the right time
add_action( 'wp_enqueue_scripts', 'call_ajax' );
add_action( 'wp_ajax_ajax_car_models', 'ajax_car_models' );
add_action( 'wp_ajax_nopriv_ajax_car_models', 'ajax_car_models' );
function ajax_car_models() {
$args = array( 'post_type' => 'product', 'posts_per_page' => 1040 );
$loop1 = new WP_Query( $args );
$code = '';
$car_make = 26;
$all_models = array();
while ( $loop1->have_posts() ) : $loop1->the_post();
$terms_make = get_the_terms( get_the_id(), 'pa_car-make' );
foreach ( $terms_make as $make ) {
if ( $make->term_id == $car_make ) {
$the_car_model = get_the_terms( get_the_id(), 'pa_model' );
foreach ( $the_car_model as $the_model ) {
if ($all_models[$the_model->name] != 'true') {
$code .= '<br />'.$the_model->name.' ';
$all_models[$the_model->name] = 'true';
}
}
}
}
endwhile;
wp_reset_postdata();
header( 'Content-type: application/json' );
echo json_encode( $code );
die();
}
还有 jQuery 本身:
jQuery( document ).ready(function() {
jQuery('#car-make').change(my_js_function);
function my_js_function()
{
jQuery.ajax({
url: my_ajax_script.ajaxurl,
dataType: 'json', // add this line
data: ({action : 'ajax_car_models'}),
success: function() {
jQuery("#feedback").html(data);
}
});
}
});
最佳答案
如果您内联包含 javascript,您将无法使用 localize
向其传递 ajax url。
您应该将 JavaScript 移至另一个文件中,然后使用 wp_enqueue_script
才能正确使用 ajax。
function call_ajax()
{
//assuming this is in a theme?
wp_enqueue_script( 'ajax_car_models', get_template_directory_uri() . '/js/ajax_car_models.js', array( 'jquery' ), null, true);
//loacalize the script using the same handle it was registered / enqueued with
wp_localize_script( 'ajax_car_models', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
//make a call to call_ajax at the right time
add_action( 'wp_enqueue_scripts', 'call_ajax' );
<小时/>
您还需要在响应函数中发送 json header
header( 'Content-type: application/json' );
echo json_encode( $code );
exit();
<小时/>
在您的 ajax 调用中,您没有将数据传递给成功回调
success: function(data){
console.log(data);
//...
}
<小时/>
您可以使用 Chrome 开发人员工具上的网络选项卡来查看实际发出的请求并检查它们收到的响应。
关于javascript - 无法让 WordPress AJAX 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23362518/