php - 在 Wordpress 自定义主题上获取 ajax 请求时出现错误 400
问题描述
我正在编写一个 Wordpress 自定义主题,在其中一个页面中,我有一个带有两个选择和一个提交按钮的表单。基本上用户可以选择两个城市并检查它们之间是否有路线。我正在使用高级自定义字段关系字段来链接城市(城市是帖子类型)。问题是我总是收到 400 错误,我不知道是什么问题。
我检查了这里找到的不同解决方案,但似乎没有一个对我有用。
管理员-ajax.php:
add_action('wp_ajax_check_route', 'check_route');
add_action('wp_ajax_nopriv_check_route', 'check_route');
function check_route() {
$id_cidade_origem = intval($_REQUEST['cidade_origem']);
$id_cidade_destino = intval($_REQUEST['cidade_destino']);
$cidades_atendidas = get_field('regioes_atendidas', $id_cidade_origem);
$tem_relacao = False;
foreach ($cidades_atendidas as $cidade) {
if($cidade->ID == $id_cidade_destino){
$tem_relacao = True;
break;
}
}
$data = array(
'success' => true,
'tem_relacao' => true
);
wp_send_json_success($data);
$data = array(
'success' => false
);
wp_send_json_error($error_data);
}
脚本.js:
jQuery("#regioes-botao").click(function (){
console.log("Clicou!");
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'check_route',
cidade_origem: jQuery('#select-from').find(":selected").val(),
cidade_destino: jQuery('#select-to').find(":selected").val(),
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (output) {
console.log('sucesso!')
console.log(output);
var resposta = output.tem_relacao;
if(resposta == true){
jQuery('#resposta span').text("Nós fazemos esta rota, entre em contato.")
}else{
jQuery('#resposta span').text("No momento não fazemos esta rota, mas já estamos trabalhando para que seja possível em breve.")
}
},
error: function(output){
console.log(output)
}
});
});
解决方案
错误代码 400 表示服务器无法理解您的原始请求。试试下面的书面代码:
$.ajax({
url: ajax_object.ajax_url, //Used wp_localize_script to pass ajax url to wordpress. Example is at https://codex.wordpress.org/AJAX_in_Plugins
type: 'POST',
data: {
'action': 'check_route',
'cidade_origem': jQuery('#select-from').find(":selected").val(),
'cidade_destino': jQuery('#select-to').find(":selected").val(),
},
})
.done(function(response) {
console.log(response);
})
.fail(function() {
})
.always(function() {
});
请注意,我只定义了请求类型、要调用的 url 和要发送的数据。我很确定这应该可以工作,因为我在我的许多项目中都使用它。
推荐阅读
- windows - 为什么使用 MS Release 库时编译器会链接到错误的方法?
- time - 如何在pytorch profiler中获取事件的walltime?
- c++ - 没有构造函数“Class:Class”的实例与参数列表匹配
- python - 有没有办法使框内下面的文本居中?
- c# - 第一条消息的 ID LINQ C#
- c# - TCPClient - 无法从传输连接读取数据:现有连接被远程主机强行关闭
- tkinter - 如何设置文本框的文本大小取决于在 tkinter 中选择了什么选项?
- python - 如何检查 abc == sqrt(a^b^c) 是否非常快(最好是 Python)?
- java - 为什么我在 Minio 中创建对象时出错?
- javascript - AJAX 分页未在新帖子中加载(未找到 admin-ajax)