wordpress - admin-ajax.php 中的 Ajax 发布调用返回 0 和 400 错误请求(Wordpress)
问题描述
您好,您可以看到我正在尝试使用 ajax post call 将我的数据发送到 admin-ajax.php 请检查下面的代码,我使用的模板是 betheme。
索引.html
$('#send-form').on('submit', function () {
$.ajax({
url : '<?php echo admin_url('admin-ajax.php'); ?>',
data : {
'action' : 'test_func',
'data':'lorem ipsum'
},
type : 'POST',
contentType: "application/json; charset=utf-8",
dataType : 'json',
success : function (callback) {
console.log(callback);
}
});
return false;
});
函数.php
function test_func () {
echo json_encode(array('res'=>'return dummy text'));
}
add_action('wp_ajax_nopriv_test_func', 'test_func');
解决方案
根据 ajax 的代码不需要添加contentType: "application/json; charset=utf-8
,因为您将数据作为字符串传递,所以contentType
不需要属性。
要解决0
每次获取的问题,您只需在方法wp_die()
末尾添加即可test_func
。
在这里你编辑了代码
1) jQuery Ajax 代码:
jQuery('#send-form').on('submit', function () {
$.ajax({
url : '<?php echo admin_url('admin-ajax.php'); ?>',
data : {
'action' : 'test_func',
'data':'lorem ipsum'
},
type : 'POST',
// contentType: "application/json; charset=utf-8",
dataType : 'json',
success : function (callback) {
console.log(callback);
}
});
return false;
});
2) 代码functions.php
function test_func () {
echo json_encode(array('res'=>'return dummy text'));
wp_die();
}
add_action('wp_ajax_nopriv_test_func', 'test_func'); // ajax call for non-login user.
add_action('wp_ajax_test_func', 'test_func'); // ajax call for login user.
推荐阅读
- react-native - react-native 中的 web3:无法读取属性“getReader”
- rxjs - rxjs中函数名中的括号
- .net - 使用 MSDeploy 部署受影响的文件
- python - 在训练和预测多类时间序列分类时保存 LSTM 隐藏状态
- c# - 更改 System.IO.Compression.ZipArchive 的排序顺序
- python - Python sklearn CountVectorizer 的分析器参数中如何识别“单词边界”?
- python - 从 KivyMD 中的 MDDropdownMenu 更改 2 个按钮的文本
- javascript - JavaScript:if 语句;对触摸元素的目标运行检查
- flutter - 如何显示双到 2 个小数点?
- forms - TYPO3 表单框架:以 HTML 和纯文本形式发送电子邮件