JQuery ajax 无法使用数据参数发布


JQuery ajax fails to post with data params

我正在尝试使用JQuery Ajax发布一个简单的联系表单,使用PHP作为处理程序。

索引.html

<form  name="signup-form" method="post" accept-charset="utf-8" class="signup-form">
   <input class="signup-input" type="email" name="email_address" value="" placeholder="enter your email..." title="Please enter a valid email address." required>
   <input type="submit" class="submit-btn" value="GO"/>
</form>

相应的 JavaScript 正确序列化了来自浏览器的输入,但我不断得到:

SyntaxError: Unexpected end of input at Object.parse (native)

JS - site.json

$(document).ready(function(){
  $(".signup-form").submit(function(e){
    var formData = $(this).serialize();
    var data = {
      "action": "test"
    };
    data = $(this).serialize() + "&" + $.param(data);
      $.ajax({
        type: "POST",
        dataType: "json",
        url: "server.php", //Relative or absolute path to response.php file
        data: data,
        success: function(data) {
          $(".the-return").html(
            "Email: " + data["email_address"]
          );
          alert("Form submitted successfully.'nReturned json: " + data["json"]);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            console.log(XMLHttpRequest);
            console.log(textStatus);
            console.log(errorThrown);
        }
      });
    return false;
  });
});

编辑的PHP - 服务器.php

<?php
header('Access-Control-Allow-Origin: *');

if (is_ajax()) {
  if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
    $action = $_POST["action"];
    switch($action) { //Switch case for value of action
      case "test": test_function(); break;
    }
  }
}
//Function to check if the request is an AJAX request
function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
  header("Content-Type: application/json");
  echo json_encode($_POST);
}

我发现了为什么它不起作用。

您的is_ajax()会检查此$_SERVER['HTTP_X_REQUESTED_WITH'],如果您使用的是 CORS,则不会设置该。因此,一个简单的解决方法是禁用此检查。

<?php
header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json");
//print_r($_SERVER);
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
  $action = $_POST["action"];
  switch($action) { //Switch case for value of action
    case "test": test_function(); break;
  }
}
function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
  $return = $_POST;
  //$return["email_address"] = json_encode($return);
  echo json_encode($return);
  exit;
}

另外不要忘记使用 data['email_address'] 访问 JSON,data['json']什么都没有。

我不确定你到底想做什么,但有一件事很明显,你的 PHP 代码返回了一个嵌套对象。

{email_address: "{"email_address":"asdf@asdf.org","action":"test"}", action: "test"}

这就是您的 JSON 在回来的路上的样子。 如果你想把_POST美元的数据吐回你的浏览器,你可以简单地做:

function test_function(){
  echo json_encode($_POST);
}

然后在JS端修改成功方法中的警报:

alert("Form submitted successfully.'nReturned json:'n" + JSON.stringify(data));

还有一件事,在 php 代码中设置内容类型标头是一个非常好的主意,可能是在您检查 X-Request-With 之后,但在您向浏览器吐出任何数据之前:

header('Content-type: application/json');