WordPress Ajax出现“错误请求”(400)错误

时间:2018-05-08 17:08:53

标签: ajax wordpress

我不明白为什么我在下面的Ajax代码中遇到400'错误请求'错误。我没有得到任何Apache错误btw:

PHP(functions.php)

function load_scripts() {
  wp_enqueue_script('jquery');  
  wp_enqueue_script('main_js', get_stylesheet_directory_uri() . '/dist/scripts/main.js', array('jquery'), true);
  wp_localize_script('main_js', 'WPaAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'load_scripts');

function send_message_function() {
  echo 'YES!';
  exit;
}

add_action('wp_ajax_send_message', 'send_message_function');
add_action('wp_ajax_nopriv_send_message', 'send_message_function');

JS(main.js)

$('.contact_form').submit(function(e) {
  e.preventDefault();
  var data = $(this).serializeArray();
  $.post(WPaAjax.ajaxurl, data, function(response) {
    $('body').append(response);
  });
});

1 个答案:

答案 0 :(得分:1)

您看到的 <body> <form id="contact-form" method="POST" class="needs-validation" onsubmit="return false" novalidate> <div class="form-group"> <label for="name">Nome</label> <input type="text" name="name" id="name" class="form-control" required /> <div class="invalid-feedback"> Please, type your name </div> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" id="email" class="form-control" required /> <div class="invalid-feedback"> Please, type your e-mail </div> </div> <div class="form-group"> <label for="subject">Assunto</label> <input type="text" name="subject" id="subject" class="form-control" /> </div> <div class="form-group"> <label for="message">Mensagem</label> <textarea name="message" id="message" class="form-control" rows="3" required minlength="10"></textarea> <div class="invalid-feedback"> Leave your message </div> </div> <button type="submit" class="btn send-btn">Enviar</button> <div id="messages" class="show_messages"></div> <div id="error_messages" class="show_error"></div> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script> (function () { 'use strict'; window.addEventListener('load', function () { var forms = document.getElementsByClassName('needs-validation'); var validation = Array.prototype.filter.call(forms, function (form) { form.addEventListener('submit', function (event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated'); if (form.checkValidity() === true) { var name = $("input#name").val(); var email = $("input#email").val(); var subject = $("input#subject").val(); var message = $("textarea#message").val(); var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message; var url = "./serverside/send-mail.php"; $.ajax({ type: "POST", url: url, data: dataString, success: function (data) { console.log(data); var response = JSON.stringify(data); console.log(response); if (data == "\"E-mail sent\"") { console.log("email sent after stringify"); $("#messages").addClass("messages") .html("<img src='./img/check.png' alt='Check' /> Message sent!") .hide().fadeIn(800, function () { setTimeout(() => { $("#messages").hide(500); }, 3000); }); $('#contact-form')[0].reset(); } else { $('#contact-form')[0].reset(); console.log("E-mail was not sent"); $("#error_messages").addClass("error_messages") .html("<img src='./img/warning.png' alt='Warning' /> Ops! Error sending your message.") .hide().fadeIn(800, function () { setTimeout(() => { $("#error_messages").hide(500); }, 3000); }); } }, error: function (e) { console.log(e); $("#error_messages").addClass("error_messages") .html("<img src='./img/warning.png' alt='Warning' /> Ops! Error sending your message.") .hide().fadeIn(800, function () { setTimeout(() => { $("#error_messages").hide(500); }, 3000); }); } }); return false; } }, false); }); }, false); })(); </script> </body> 错误消息是因为WordPress认为您的请求等待它 - 无效:

  1. 当您需要普通对象或字符串时,您将对象数组传递给$.post。您想要使用FormData代替:

    Bad Request
    1. WordPress希望$('.contact_form').submit(function(e) { e.preventDefault(); var data = new FormData($(this)[0]); $.post(WPaAjax.ajaxurl, data, function(response) { $('body').append(response); }); }); 参数包含在您的请求中,而您的代码似乎缺少该参数。所以:

      action