亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 167 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號