【问题标题】:Getting error 400 on ajax request on Wordpress custom theme在 Wordpress 自定义主题上获取 ajax 请求时出现错误 400
【发布时间】: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 它也​​没有用:(
  • 好的,我确信会起作用的一件事,我将在答案中添加它。

标签: php jquery ajax wordpress


【解决方案1】:

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

【讨论】:

  • 谢谢,但它对我不起作用。但我得到了它的工作,只是用代码制作了一个“模板”,并对那个页面而不是 /wp-admin/admin-ajax.php 提出了一个获取请求
  • @Luc url: ajax_object.ajax_url, 指向通过将参数本地化到脚本文件来传递给文件的ajax url。如果您在模板中执行此操作,请使用 POST 而不是 GET 并确保正确清理输入和输出。
猜你喜欢
  • 1970-01-01
  • 2019-01-12
  • 2022-01-17
  • 1970-01-01
  • 2016-01-06
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
相关资源
最近更新 更多