【问题标题】:PHP not receiving AJAX POST from js FilePHP没有从js文件接收AJAX POST
【发布时间】:2020-10-22 15:25:58
【问题描述】:

我已经尝试解决这个问题几个小时了,但找不到任何对我有帮助的答案。

这是我的 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

更新:函数 console_log() 存在于我的 PHP 文件中,并且可以正常工作

【问题讨论】:

  • 试试data: { Name: name }, 并告诉我?
  • 在外面尝试var_dump($_REQUEST),并检查您是否收到请求

标签: javascript php ajax web


【解决方案1】:

尝试以 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);

}

【讨论】:

    【解决方案2】:

    我通过以下操作修复了它:

    我在 game.php 中添加了以下 HTML 代码(用于调试目的)

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

    还在我的game.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;
        }
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-03
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多