我知道这个问题已经被问了很多,所以我为任何冗余道歉。但是,似乎无法使其返回0以外的值。以下是我在Twenty-Twelve主题中包含在functions.php底部的代码:
add_filter( 'views_edit-destination', 'so_13813805_add_button_to_views' );
function so_13813805_add_button_to_views( $views )
{
$views['my-button'] = '<button id="update-dest-cache" type="button" class="button" title="Update Destinations Cache" style="margin:5px" onclick="updateDestCache()">Update Destinations Cache</button>';
$views['my-button'] .= '
<script type="text/javascript" >
function updateDestCache() {
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: "json",
action: "testAjaxFunction",
success: function(response){
alert("Got this from the server: " + response);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert("There was an error: " + errorThrown);
},
timeout: 60000
});
};
</script>
';
return $views;
}
function testAjax(){
echo "ANYTHING!!!!";
die();
}
add_action('wp_ajax_testAjaxFunction', 'testAjax');
add_action('wp_ajax_nopriv_testAjaxFunction', 'testAjax' );
此代码在自定义帖子类型的“编辑”列表中添加一个按钮,然后在单击时运行该功能。按钮显示,函数运行,调用ajax函数,但0始终是响应。
关于为什么会这种情况继续发生的任何想法?
答案 0 :(得分:2)
我的javascript写得不正确。
function updateDestCache() {
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: { action: "testAjaxFunction" }, <---- THIS LINE WAS CHANGED
success: function(response){
alert("Got this from the server: " + response);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert("There was an error: " + errorThrown);
},
timeout: 60000
});
};
答案 1 :(得分:0)
ajaxurl
仅在信息中心内定义。如果你在前端使用它,你应该声明它:
$admin_url = admin_url('admin-ajax.php');
$views['my-button'] .= '
<script type="text/javascript" >
function updateDestCache() {
jQuery.ajax({
type: "POST",
url: '. $admin_url .',
dataType: "json",
action: "testAjaxFunction",
success: function(response){
alert("Got this from the server: " + response);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert("There was an error: " + errorThrown);
},
timeout: 60000
});
};
</script>
';