ReferenceError:未定义ajax_object

问题描述 投票:-1回答:2

嗨我有链接点击时这个脚本将数据保存到数据库中。现在我的问题是在点击链接后这是错误:

ReferenceError: ajax_object is not defined

这是我在单一知识页面中的脚本

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $(".dL").click(function(){
            var name = ($(this).attr('name'));
            var urldata = ($(this).attr('href'));

            var data = {
                'action': 'my_action',
                'name': name,
                'urldata': urldata // We pass php values differently!
            };


            // We can also pass the url value separately from ajaxurl for front end AJAX implementations
            jQuery.post(ajax_object.ajax_url, data, function(response) {
                // alert('Got this from the server: ' + response);
                alert(response);
            });

        });


    });

</script>

这是我下面的function.php脚本

 function my_action(){
        global $wpdb; // this is how you get access to the database

        $name = $_POST['name'];
        $url = $_POST['urldata'];


        $wpdb->insert('list_of_downloads', array(
            'name' => $name,
            'filename' =>$url
        ));

       // wp_die(); // this is required to terminate immediately and return a proper response
    }


    add_action( 'wp_ajax_my_action', 'my_action' );
    add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // <= this one

问题是这一个ajax_object有人可以帮我弄清楚这件事吗?任何帮助都非常值得赞赏。 TIA

php wordpress
2个回答
0
投票

您收到错误是因为您没有声明该变量。因为你试图通过使用wordpress的ajax调用函数,所以我想分享我最近做过的事情。

在function.php中添加以下脚本,这将在标题中添加admin-ajax.php url。

add_action( 'init', 'my_script_enqueuer' );

function my_script_enqueuer() {
    wp_enqueue_script( 'add-order-front',  get_template_directory_uri() . '/js/ajax.js' );
    wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'add-order-front' );

}

然后使用以下ajax脚本来调用该函数。

jQuery(document).on('click','.dL',function(){
    var name = ($(this).attr('name'));
    var urldata = ($(this).attr('href'));
    jQuery.ajax({
        type : 'POST',
        url  : MyAjax.ajaxurl,
        data: {action: 'my_action','name': name,'urldata': urldata}, 
        dataType:"json",
        success:function(data){
            console.log(data);                  
        },
        error: function(data){
            console.log(data);
        }
    });
});

上面的脚本对我有用。


0
投票

我没有看到你声明'ajax_object'的任何地方。您可以像下面一样使用它,如果您的服务器端代码在'function.php'文件中:

// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post("function.php", data, function(response) {
   // alert('Got this from the server: ' + response);
   alert(response);
});
© www.soinside.com 2019 - 2024. All rights reserved.