簡體   English   中英

JavaScript AJAX XMLHttpRequest 上“發布”請求回調 ZC1C425268E6838385D1AB5Z074C“工作”

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

在這里,我嘗試使用 AJAX 將數據發送到服務器,在服務器端我使用了 PHP,我使用了 post 請求,數據成功發送到服務器並發送消息到客戶端,但在客戶端“onload” " 回電 function 不會被調用。 請幫忙。

這里是前端代碼:

<!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>

這是 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')
    );
  }

我已經使用 api 測試儀測試了服務器代碼,它工作正常也給出了響應。 唯一的問題是創建了用戶,但沒有調用 onload function。

在調用 send( onload() )。 在調用 send 之后調用它。 當您將其分配給 onload 時,您並沒有調用它。 您只是在定義它,以便當 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 文檔示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM