Php $\u GET从Ajax fetch()返回null

Php $\u GET从Ajax fetch()返回null,php,ajax,Php,Ajax,所以,我在做一个琐事游戏。这是我的PHP代码和Ajax代码。问题是,无论我做什么,php代码中的变量$categoryName总是返回null。因此,在我的JS代码中,当我尝试获取url时,我不断得到以下错误:“Uncaught(in promise)SyntaxError:Unexpected token.in JSON位于位置0 在parse()处“ 这段代码还没有完成,但这个问题阻碍了我前进。有什么想法吗?这是AMPS服务器上的两个不同文件 PHP文件 /* Step 2: Write

所以,我在做一个琐事游戏。这是我的PHP代码和Ajax代码。问题是,无论我做什么,php代码中的变量$categoryName总是返回null。因此,在我的JS代码中,当我尝试获取url时,我不断得到以下错误:“Uncaught(in promise)SyntaxError:Unexpected token.in JSON位于位置0 在parse()处“

这段代码还没有完成,但这个问题阻碍了我前进。有什么想法吗?这是AMPS服务器上的两个不同文件

PHP文件
/* Step 2:  Write a trivia.php code to read the .txt files (from particular category specified by the fetch()) and output as JSON.  You can use $_GET[“mode”], scandir and json_encode(). 


What you need to do is given the category query parameter from the trivia.js, create a random question  (e.g. using array_rand()) send it back to the browser.

*/

//handles category names
$triviafiles = "trivia/"; //questions and answers themselves
$files = scandir("trivia/");
$categories = implode('<br>', $files);
echo $categories;

//gets questions
$categoryName = strtolower($_GET["name"]); //always is null. Don't know why

$trivia = glob($triviafiles.$categoryName."/*.txt"); 
//categoryName still shows up as Null. Hardcoding a name in works, but that obviously defeats the purpose. 

foreach($trivia as $question){
    $answer = file_get_contents($question);
}

echo(json_encode(array("question" => $question, "answer" => $answer)));

?>
/*步骤2:编写一个trivia.php代码来读取.txt文件(来自fetch()指定的特定类别)并作为JSON输出。您可以使用$_GET[“mode”]、scandir和json_encode()。
您需要做的是从trivia.js中获得category query参数,创建一个随机问题(例如使用array_rand())并将其发送回浏览器。
*/
//处理类别名称
$triviafiles=“trivia/”//问题和答案本身
$files=scandir(“琐事/”);
$categories=内爆(“
”,$files); echo$类别; //得到问题 $categoryName=strtolower($_GET[“name”])//始终为空。不知道为什么 $trivia=glob($triviafiles.$categoryName./*.txt”); //categoryName仍然显示为Null。在工作中硬编码一个名字,但这显然违背了目的。 foreach($问题中的琐事){ $answer=文件获取内容($question); } echo(json_编码(数组(“问题”=>$question,“答案”=>$answer))); ?>
JavaScript文件

/* Step 2:  Write a trivia.php code to read the .txt files (from particular category specified by the fetch()) and output as JSON.  You can use $_GET[“mode”], scandir and json_encode(). 


What you need to do is given the category query parameter from the trivia.js, create a random question  (e.g. using array_rand()) send it back to the browser.

*/

//handles category names
$triviafiles = "trivia/"; //questions and answers themselves
$files = scandir("trivia/");
$categories = implode('<br>', $files);
echo $categories;

//gets questions
$categoryName = strtolower($_GET["name"]); //always is null. Don't know why

$trivia = glob($triviafiles.$categoryName."/*.txt"); 
//categoryName still shows up as Null. Hardcoding a name in works, but that obviously defeats the purpose. 

foreach($trivia as $question){
    $answer = file_get_contents($question);
}

echo(json_encode(array("question" => $question, "answer" => $answer)));

?>
window.onload = function () {
    "use strict";
    let showCat = document.getElementById("view-all");
    showCat.onclick = fetchCategories;
    let show_answer = document.createElement("button");
    show_answer.classList.add("controls");
    show_answer.innerHTML += "Show Answer";
    document.getElementById("question-view").append(show_answer);
//    show_answer.onclick = 

};



function displayCategories() {
    document.getElementById("categories-heading").className = null;
    document.getElementById("category-view").className = null;

}

function selectedText(category){
    let categories = document.querySelectorAll("li");
    for(let i = 0; i<categories.length; i++){
        categories[i].classList.remove("selected-category");
    }
    category.classList.add("selected-category");
    category.onclick = showTrivia;
}


function fetchCategories() {     
    let hrx = new XMLHttpRequest();     
    hrx.onload = displayCategories;
    hrx.open("GET", "trivia.php?mode=category");
    hrx.send();
    hrx.onreadystatechange=function(){
        if(hrx.readyState === 4 && hrx.status === 200) {
            let list = hrx.responseText;
            list=list.split("<br>");
            for (let i = 0; i<list.length; i++){
                let category = document.createElement("li");
                category.innerHTML += list[i];
                document.getElementById("categories").appendChild(category);
            }
        }

        let categories = document.querySelectorAll("li");
        for(let i = 0; i<categories.length; i++){
            categories[i].classList.remove("selected-category");
            categories[i].addEventListener("click",function(){selectedText(categories[i])}, false);
        }

    }
}

    //include this code, based on: https://developers.google.com/web/updates/2015/03/introduction-to-fetch
    function checkStatus(response){  
        if (response.status >= 200 && response.status < 300) {  
            return response.text();
        }else{
            return Promise.reject(new Error(response.status + ": " + response.statusText));
        } 
    }
function displayQuestion() {
    document.getElementById("question-view").className = null;
    document.getElementById("card").className = null;
}

function showTrivia() {
    let currentCategory = document.querySelector(".selected-category");
    console.log(currentCategory);
    let url = "trivia.php?mode=category";
    url += "&name=" + currentCategory.innerHTML;
    console.log(url);

     fetch(url, {method: "GET"})     
     .then(checkStatus)
     .then(JSON.parse) // main issue. Parsing error    
     .then(displayQuestion);

    }
window.onload=函数(){
“严格使用”;
让showCat=document.getElementById(“查看全部”);
showCat.onclick=fetchCategories;
让show_answer=document.createElement(“按钮”);
show_answer.classList.add(“控件”);
show_answer.innerHTML+=“show answer”;
document.getElementById(“问题视图”).append(显示答案);
//show_answer.onclick=
};
函数displayCategories(){
document.getElementById(“类别标题”).className=null;
document.getElementById(“类别视图”).className=null;
}
功能选择文本(类别){
让categories=document.queryselectoral(“li”);
for(让i=0;i(我还不能发表评论,但这是我的看法:)
正如其他人所解释的,您有两个对trivia.php的AJAX调用

在第一个示例中(当用户单击“全部查看”时),您不在GET中指定名称

在第二个示例中(当用户单击特定类别时),您可以在GET中指定名称

在trivia.php的第一次加载期间,$categoryName为null是合乎逻辑的,因为您没有指定它
您确定您也在检查trivia.php的第二次加载吗?因为当时似乎应该填写$categoryName。

当页面第一次加载时,php代码会运行,但是AJAX获取直到用户单击该类别时才会发生。初始加载的URL中没有
name=
。@barmar,我该如何处理这?我理解错误,但我对PHP了解不够,无法理解如何在Ajax中进行特定的PHP调用。请将服务器端Ajax(PHP)和客户端Ajax(HTML&js)的页面分开。客户端AJAX可以调用服务器端AJAX,而服务器端AJAX只有在需要时才会运行。@malovich,对不起,我没有说清楚,这已经是两个独立的文件了。这会像创建两个独立的PHP函数一样简单吗?@LukeTheuma啊,不会。接下来我注意到的是,您正在寻找一个
名称
e$\u GET但是只发送一个
模式
。如果不发送PHP代码正在查找的密钥,它将发送一个通知级别的错误,并在默认情况下用
null
填充缺少的密钥。谢谢!问题,您是否建议只创建从GET开始的url?类似于hrx.open(“GET”,“trivia.PHP?mode=category&name=”);关于第一次加载?另外,可能我没有检查它,但我不确定如何检查第一次加载与第二次加载。这就是为什么人们建议您使用两个单独的php文件。第一次加载使用1个,第二次加载使用第二个!谢谢大家!!