簡體   English   中英

PHP 未從 js 文件接收 AJAX POST

[英]PHP not receiving AJAX POST from js File

我一直在努力解決這個問題幾個小時,但找不到任何對我有幫助的答案。

這是我的 javascript 文件中的代碼

function sendMovement(cel) {
  var name = "test";
  $.ajax({
      type: 'POST',
      url: '../game.php',
      data: { 'Name': name },
      success: function(response) {
          console.log("sent");
      }
  });
}

這是我的 PHP 文件中的代碼(它在 js 文件之外)

if($_SERVER["REQUEST_METHOD"] == "POST") {
  $data = $_POST['Name'];
  console_log($data);
}

調試時我可以看到 AJAX 正在發送一個 POST 並且它確實在控制台“SENT”中打印但它不打印 $data

更新: function console_log() 存在於我的 PHP 文件中,它可以工作

嘗試以 JSON 格式獲取響應,因為您的 js 應該具有 dataType:'JSON' 如下所示

JS代碼:-

function sendMovement(cel) {
  var name = "test";
  $.ajax({
      type: 'POST',
      dataType:'JSON',   //added this it to expect data response in JSON format
      url: '../game.php',
      data: { 'Name': name },
      success: function(response) {
          //logging the name from response
          console.log(response.Name);
      }
  });
}

並且在當前的服務器端代碼中,您沒有回顯或返回任何內容,因此無論如何 ajax 響應中都不會顯示任何內容。

php 服務器代碼的更改:-

if($_SERVER["REQUEST_METHOD"] == "POST") {
  
  $response = array();
  $response['Name'] = $_POST['Name'];
  //sending the response in JSON format
  echo json_encode($response);

}

我通過執行以下操作來修復它:

在我的游戲中。php 我添加了以下 HTML 代碼(用於調試目的)

<p style = "color: white;" id="response"></p>

在我的游戲中還添加了php以下

if($_SERVER["REQUEST_METHOD"] == "POST") {
  
  $gameID = $_POST['gameID'];
  $coord = $_POST['coord'];
  $player = $_POST['player'];

  echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;

}

並且在我的 custom.js 中我更新了

function sendMovement(cel) {
  var handle = document.getElementById('response');
  var info = [gameID, cel.id, current_player];

  $.ajax({
    type: 'POST',
    url: '../game.php',
    data: {
      gameID: info[0],
      coord: info[1],
      player: info[2]
    },
    success: function(data) {
      handle.innerHTML = data;
    },
    error: function (jqXHR) {
      handle.innerText = 'Error: ' + jqXHR.status;
    }
  });
}

暫無
暫無

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

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