简体   繁体   English

JavaScript AJAX XMLHttpRequest 上“发布”请求回调 ZC1C425268E6838385D1AB5Z074C“工作”

[英]JavaScript AJAX XMLHttpRequest on "Post" request the call back function "onload" does work

Here I have tried to use AJAX for sending data to server, In server side I have used PHP,I used post request, data gets sent to the server successfully and also sends message to the client side, but on the client side the "onload" call back function doesn't get called.在这里,我尝试使用 AJAX 将数据发送到服务器,在服务器端我使用了 PHP,我使用了 post 请求,数据成功发送到服务器并发送消息到客户端,但在客户端“onload” " 回电 function 不会被调用。 Please Help.请帮忙。

Here the frontend code:这里是前端代码:

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">

    function postUser() {
      if(validityCheck()) {
          let xhr = new XMLHttpRequest();
              xhr.open("POST", "./api/user/create.php", true);
              xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
              xhr.send(extractFormValues());
            xhr.onload = function() {
                alert("Hi");
            }
      }
      else {
        alert("Please fill the form correctly");
      }

    }

    function validityCheck() {
        if(document.getElementById("name").checkValidity()) {
            if(document.getElementById("age").checkValidity()) {
                return true ;
            }
        }
        else {
            return false ;
        }
    }

    function extractFormValues() {
        let nam = document.getElementById("name").value;
        let age = document.getElementById("age").value;
        let user = {"name":nam,"age":age}
        return (JSON.stringify(user))
    }
</script>
<div>
  <h2>Let AJAX</h2>
    <form method="post">
      <label for="name">Name:</label><br>
      <input type="text" id="name" name="name" required><br>
      <label for="age">Age:</label><br>
      <input type="text" id="age" name="age"><br><br>
      <input type="submit" value="Submit" onclick="postUser()">
    </form>
</div>

</body>
</html>

Here is the server side code in php:这是 php 中的服务器端代码:

<?php
  // Headers
  header('Access-Control-Allow-Origin: *');
  header('Content-Type: application/json');
  header('Access-Control-Allow-Methods: POST');
  header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization,X-Requested-With');

  include_once '../../config/Database.php';
  include_once '../../models/User.php';
  // Instantiate DB & connect
  $database = new Database();
  $db = $database->connect();

  // Instantiate blog post object
  $user = new User($db);

  // Get raw posted data
  $data = json_decode(file_get_contents("php://input"));

// need to check the data is valid or not

  $user->name = $data->name;
  $user->age = $data->age;

  // Create Category
  if($user->create()) {
    echo json_encode(
      array('message' => 'User Created')
    );
  } else {
    echo json_encode(
      array('message' => 'User Not Created')
    );
  }

I have tested the server code using api tester it works fine also gives the response.我已经使用 api 测试仪测试了服务器代码,它工作正常也给出了响应。 The only problem is the user gets created but the onload function doesn't gets called.唯一的问题是创建了用户,但没有调用 onload function。

You have to call onload() before you call send().在调用 send( onload() )。 It's called after send is called.在调用 send 之后调用它。 When you assign it to onload, you're not calling it.当您将其分配给 onload 时,您并没有调用它。 You're just defining it so that it's there when XHR needs to call it.您只是在定义它,以便当 XHR 需要调用它时它就在那里。

let xhr = new XMLHttpRequest();
          xhr.open("POST", "./api/user/create.php", true);
          xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
          xhr.onload = function() {
                  alert("Hi");
               };
          xhr.send(extractFormValues());

MDN Docs Example MDN 文档示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM