【问题标题】:Why am I getting a 400 error when I'm trying to load a post using AJAX in WordPress?当我尝试在 WordPress 中使用 AJAX 加载帖子时,为什么会收到 400 错误?
【发布时间】:2021-03-19 10:22:54
【问题描述】:

目标:使用 AJAX 显示帖子标题和内容。

到目前为止我做了什么:

在functions.php中加载custom.js并本地化AJAX:

wp_enqueue_script( 'custom_js', get_stylesheet_directory_uri() . '/custom.js', array( 'jquery' ) );
wp_localize_script( 'custom_js', 'ajax_object', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        ));

在functions.php中制作一个函数来获取帖子的标题和内容:

function my_load_ajax_content () {

    $pid        = intval($_POST['post_id']);
    $the_query  = new WP_Query(array('p' => $pid));

    if ($the_query->have_posts()) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();

            $data = '
            <div class="post-container">
                <div id="postdata">
                    <h1 class="entry-title">'.get_the_title().'</h1>
                    <div class="entry-content">'.get_the_content().'</div>
                </div>
            </div>  
            ';

        }
    } 
    else {
        echo '<div id="postdata">'.__('Didnt find anything', THEME_NAME).'</div>';
    }
    wp_reset_postdata();


    echo '<div id="postdata">'.$data.'</div>';
}

add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' );

在 custom.js 中做 AJAX 的东西:

jQuery(document).ready(function(){

jQuery.post(ajax_object.ajaxurl, {
        action: 'my_load_ajax_content ',            
        post_id: 17521  // << should grab this from input...

    }, function(data) {

        var $response   =   jQuery(data);
        var postdata    =   $response.filter('#postdata').html();

        jQuery('.stickithere').html(postdata);
    });

最后在页面上给它一个加载位置:

<div class="stickithere"></div>

我收到 400 错误,我不知道为什么,但我猜这与本地化 AJAX 有关,因为这似乎是我最近大部分噩梦的原因。

【问题讨论】:

  • 错误信息告诉你什么?您尝试过什么来解决问题?
  • localising AJAX 是什么意思?如果所有信息设置正确,您是否检查过网络选项卡?

标签: jquery ajax wordpress


【解决方案1】:

我认为,这就是问题所在: add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' );load-content - 是动作的名称,由 AJAX 传递。但是你通过action: 'my_load_ajax_content'。所以试着像这样改变你的行为:

add_action ( 'wp_ajax_nopriv_my_load_ajax_content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_my_load_ajax_content', 'my_load_ajax_content' );

【讨论】:

  • 太棒了,解决了!您不会知道如何使用自定义帖子类型进行这项工作吧?
  • 当然。您需要将post_type =&gt; 'your_cpt' 添加到 WP_Query 的参数数组中。更多信息在这里developer.wordpress.org/reference/classes/wp_query/…
  • 太棒了。所以我只是将 the_query 更改为: ` $the_query = new WP_Query(array( 'p' => $pid, 'post_type' => 'market', 'post_status' => 'publish', 'orderby' => 'title' , 'order' => 'ASC', ));` 现在可以了!
  • 很高兴听到它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 2014-12-06
  • 2021-03-27
  • 2021-12-15
  • 2023-03-12
  • 2019-03-22
  • 1970-01-01
相关资源
最近更新 更多