为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 未从 js 文件接收 AJAX POST

PHP 未从 js 文件接收 AJAX POST

PHP
斯蒂芬大帝 2023-07-08 20:37:05
我已经尝试解决这个问题几个小时了,但找不到任何对我有帮助的答案。这是我的 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 文件中并且可以工作
查看完整描述

2 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

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


}


查看完整回答
反对 回复 2023-07-08
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

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


在我的 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;

    }

  });

}


查看完整回答
反对 回复 2023-07-08
  • 2 回答
  • 0 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信