2

在 WordPress 的前端调用 Ajax 无法正常工作,我只想从基于 id 的 db 中获取数据,这是我迄今为止尝试过的。

//Frontend view

<a href="javascript:void(0)" onclick="getDetails(<?=$index;?>)" >
        <?php echo $value ?>
    </a>

//Functions.php

function my_enqueue() {
      wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/assets/js/ajax-script.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
 }

 add_action( 'wp_enqueue_scripts', 'my_enqueue' );
 add_action('wp_ajax_nopriv_more_posts', 'get_more_posts');

function get_more_posts(){
    // How to get id here to query for the database
    echo "Hello World";
    exit(); 
}

// Ajax scripts File
function getDetails(id)
{
jQuery.ajax({
    url: more_posts.ajax_url,
    type: "GET",
    data: {
        action: 'more_posts'
    },
    dataType: "html",
    success: function(response){
        alert(response);
    }
});
}

我收到此错误

参考错误 more_posts 未定义

4

2 回答 2

3
//Frontend view

<a href="javascript:void(0)" onclick="getDetails(<?=$index;?>)" >
        <?php echo $value ?>
    </a>

//Functions.php

function my_enqueue() {
      wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/assets/js/ajax-script.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
 }

 add_action( 'wp_enqueue_scripts', 'my_enqueue' );
 add_action('wp_ajax_nopriv_more_posts', 'get_more_posts');

function get_more_posts(){
    // How to get id here to query for the database
    echo "Hello World";
    echo $_GET['id'];
    exit(); 
}

// Ajax scripts File
function getDetails(id)
{
var id = id;
jQuery.ajax({
    url:  url: my_ajax_object.ajax_url,
    type: "GET",
    data: {
        action: 'get_more_posts',
        id: id,
    },
    dataType: "html",
    success: function(response){
        alert(response);
    }
});
}

这应该工作!您不需要绝对路径或带有 ' href', 的 varurl: my_ajax_object.ajax_url就足够了,因为您已经添加了 admin-ajax.php 和wp_enqueue_script. 谢谢

于 2017-08-29T12:28:55.593 回答
1

你误入

  url: more_posts.ajax_url

因为您本地化脚本名称是 my_ajax_object

 wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

尝试这个

 url: my_ajax_object.ajax_url
于 2017-08-29T12:32:00.850 回答