我正在使用 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/