javascript - (WordPress/Ajax) 引用错误 : Can't find variable: ajaxobject

标签 javascript php jquery ajax wordpress

我正在使用 Wordpress + Ajax,即使使用正确的钩子(Hook),我也会收到错误“ReferenceError: Can't find variable: ajaxobject”。当然我的 ajaxurl 有一些问题,但我不明白在哪里,因为它对我来说似乎做得很好。你能帮帮我吗?

在我的 functions.php 中

add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file', 11, 2 );
function add_frontend_ajax_javascript_file()
{
   wp_localize_script( 'ajax-script', 'ajaxobject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

我的 jQuery/AJAX 文件

var itemtitle = $('#itemtitle').val();
    var itemdescription = $('#itemdescription').val();
    jQuery.ajax({
        method: 'post',
        url : ajaxobject.ajaxurl, //Why???
        dataType: "json",
        data: {
            'action':'update_portfolio_function',
            'pid' : id,
            'itemtitle' : itemtitle,
            'itemdescription' : itemdescription,
        },
        success:function(data) {
            // This outputs the result of the ajax request
            alert("Coooool");
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }

    });

当然 update_portfolio_function 看起来像

add_action('wp_ajax_update_portfolio', 'update_portfolio_function' );
function update_portfolio_function(){
    $id = $_REQUEST['pid'];
    $title = $_REQUEST['itemtitle'];
    $description = $_REQUEST['itemdescription'];
    $attachment = array(
        'ID' => $id,
        'post_title' => $title,
        'post_content' => $description
    );
    // now update main post body
    wp_update_post( $attachment );
    die();
}

我应该使用 init 还是 no_priv

最佳答案

你只需要使用 ajaxurl 而不是 ajaxobject.ajaxurl

喜欢下面

jQuery.ajax({
        method: 'post',
        url : ajaxurl,
        dataType: "json",

关于javascript - (WordPress/Ajax) 引用错误 : Can't find variable: ajaxobject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502487/

相关文章:

jquery - Foundation Equalizer 设置高度继承?

javascript - jquery动态添加表单字段问题

javascript - 根据选择选择一些复选框

javascript - 在提交表单之前显示视频

php - MySQL 只更新一半的查询

php - 使用 Jquery/ajax 将数据发送到数据库

javascript - 如何在溢出隐藏div上使用鼠标滚动事件

javascript - 如何区分两个非常接近的数字?

javascript - jQuery:我们不能将 jQuery(this) 分配给一个变量吗?

javascript - 在 jquery 中单击按钮获取父级(仅属于特定类)的索引