更新: 我设法让 AJAX 工作,但不是在点击事件中。 我更新了问题以匹配这个。
我正在尝试在页面上找到的一些代码:“插件中的 AJAX”。
但是我无法让它工作,而且我真的不知道从哪里开始寻找。 当我删除点击功能并仅在页面加载时运行代码时,它会起作用。
我有一个看起来像这样的 Javascript 文件:
jQuery(document).ready(function(){
jQuery("#createremotesafe").click(function(){
alert ('test');
var data = {
action: 'my_action',
whatever: 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
});
在我的 PHP 脚本中某处生成应该执行 Javascript 的按钮(即管理页面),以及页面的其余部分:
add_action('wp_ajax_my_action', 'my_action_callback');
echo 'test2';
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = $_POST['whatever'];
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
我得到了 Alert ('test')
和 echo 'test2'
,但不是响应警报。 没有 Javascript 错误或任何东西。 我的代码确实在运行,因为我可以看到两个“测试”,但为什么 AJAX 没有得到任何响应? 页面加载后我的 php 函数会消失吗? 也许我不能/不应该使用内置的 wp AJAX 函数?
它也没有显示一个空的警告框,只是什么也没有发生。
从工作代码库开始..
add_action('in_admin_header', 'my_ajax_button');
function my_ajax_button() {
echo '<a href="#ajaxthing" class="myajax">Test</a>';
}
add_action('admin_head', 'my_action_javascript');
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$('.myajax').click(function(){
var data = {
action: 'my_action',
whatever: 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
});
</script>
<?php
}
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = $_POST['whatever'];
$whatever += 10;
echo $whatever;
exit(); // this is required to return a proper result & exit is faster than die();
}
这是来自 codex 页面的代码(稍作调整),这对我来说非常好,所以我建议使用它作为起点..如果那是你最初所做的,它在什么时候中断或停止工作?
笔记: Mark 是我,我在从另一台 PC(不是我的)访问该站点时使用辅助帐户。
