【发布时间】:2019-07-02 11:11:39
【问题描述】:
我正在编写一个 Wordpress 自定义主题,在其中一个页面中,我有一个带有两个选择和一个提交按钮的表单。基本上用户可以选择两个城市并检查它们之间是否有路线。 我正在使用高级自定义字段关系字段来链接城市(城市是帖子类型)。 问题是我总是收到 400 错误,我不知道是什么问题。
我检查了这里找到的不同解决方案,但似乎没有一个适合我。
admin-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);
}
scripts.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)
}
});
});
【问题讨论】:
-
尝试更改代码如下:
data: { 'action': 'check_route', 'cidade_origem': jQuery('#select-from').find(":selected").val(), 'cidade_destino': jQuery('#select-to').find(":selected").val(), }, contentType: "application/json", -
嗨@FahamShaikh,感谢您的回复。不幸的是,它没有奏效,您还有其他想法吗?
-
嗯,我唯一能想到的就是删除
contentType,因为有时它会导致错误。并将您的数据序列化为data: JSON.stringify({ 'action': 'check_route', 'cidade_origem': jQuery('#select-from').find(":selected").val(), 'cidade_destino': jQuery('#select-to').find(":selected").val(), }), -
@FahamShaikh 它也没有用:(
-
好的,我确信会起作用的一件事,我将在答案中添加它。