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);
}

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;
}
});
}
- 2 回答
- 0 關注
- 167 瀏覽
添加回答
舉報