2017-10-11 35 views
0

我需要一些幫助。我無法使用JavaScript做POST請求..我不想首先使用jQuery。我不知道爲什麼我的$ _POST是空的。我該如何正確製作AJAX POST請求

這是我的scores.php文件。

<?php 

$method = $_SERVER['REQUEST_METHOD']; 
$file = __DIR__ . '/scores.json'; 
$scores = file_get_contents($file); 

if ($method === 'GET') { 
echo $scores; 
} else if ($method === 'POST') { 
$scores = json_decode($scores, TRUE); 
$scores[] = [ 
    'name' => $_POST['name'], 
    'scores' => (int) $_POST['scores'], 
]; 

usort($scores, function($a, $b) { 
    $scoresA = $a['scores']; 
    $scoresB = $b['scores']; 

    if ($scoresA === $scoresB) { 
     return 0; 
    } 

    return $scoresA < $scoresB ? 1 : -1; 
}); 

$scores = json_encode($scores); 

file_put_contents($file, $scores); 

echo $scores; 
} else { 
echo 'Method not allowed.'; 
} 

這是我的一些代碼frogGame.js文件:

function setScores(){ 
let xhttp = new XMLHttpRequest(); 
xhttp.open("POST", "scores.php", true); 
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
xhttp.send("name=Henry&scores=2542"); 

} 

setScores(); 
+0

您記錄查詢字符串,但期待JSON。將POST更改爲GET並查看是否獲取了任何內容,然後簡化POST,直到獲得某些內容,然後開始添加更復雜的代碼 – mplungjan

回答

0

你應該使用這樣的:

function setScores(){ 
    let xhttp = new XMLHttpRequest(); 
    xhttp.open("POST", "scores.php?name=Henry&scores=2542", true); 
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhttp.send(); 
} 
setScores();