有4个过滤器可用于WordPress ajax。根据您的描述,假设以下条件
代码中有一些问题,下面是我进行测试所需的带有缺失片段的修复脚本。我将代码放入了我的主题中
functions.php
和javascript代码
test.php
在测试中,加入了主题函数。php
// load the javascript
function q364077_enqueue_scripts()
{
wp_enqueue_script(\'test-custom-scripts\', get_theme_file_uri(\'/test.php\'), array(), \'t\' . time(), true);
}
add_action(\'wp_enqueue_scripts\', \'q364077_enqueue_scripts\', 101);
// The ajax answer()
add_action( \'wp_ajax_my_action\', \'answer\' );
function answer() {
// check_ajax_referer( \'nonce-name\' );
echo "hello";
wp_die(); // terminate script after any required work, if not, the response text will output \'hello0\' because the of function return after finish
}
测试。php被放在主题文件夹中,与函数级别相同。php
<?php
// inside the javascript test.php
/** Load WordPress Bootstrap */
// for test.php in theme folders
require_once( ( ( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) ) ) . \'/wp-load.php\' ); // to use admin_url(), if not, the script will be broken
// for output the javascript through php
header("Content-type: text/javascript");?>
function myFunction() {
let dataContent = "hello";
let myData = {
_ajax_nonce: "<?php echo wp_create_nonce( \'nonce-name\' );?>", // haven\'t added echo here, it is actually blank in output.
// Action Hook name for Ajax Call
action: \'my_action\',
// Currently typed username
data: dataContent
};
// To send the JavaScript object to the server, convert it into a JSON string
let myDataJSON = JSON.stringify(myData);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
let link = "<?php echo admin_url( \'admin-ajax.php\' );?>"; // require "echo" to output, otherwise, it will alert unexpected output
xhttp.open("POST", link, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
// It is explained in the following, I use static value for illustration purpose
xhttp.send(\'_ajax_nonce=efc5e4029d&action=my_action&data=hello\');
数据需要序列化,而不仅仅是字符串。您的数据看起来像
{"_ajax_nonce":"efc5e4029d","action":"my_action","data":"hello"}
Ajax寻找jQuery为用户所做的。对于Vanilla JS,需要手动或使用任何现有的Vanilla JS工具来完成。
_ajax_nonce=efc5e4029d&action=my_action&data=hello
您可以通过修复“echo”并输入数据的静态值来测试上述代码,也可以访问检查器,例如Chrome。
在inspector->Network选项卡->当您在控制台日志中启动myFunction()时,它会使用请求/响应头将状态返回给您,这样有助于修复bug。
以上代码在新的WordPress 5.3.2中进行了测试,并证明其工作正常,默认为二十个二十主题。