首页 > 解决方案 > 在 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)
            }
        });
    });

标签: phpjqueryajaxwordpress

解决方案


错误代码 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 和要发送的数据。我很确定这应该可以工作,因为我在我的许多项目中都使用它。


推荐阅读