$ _GET从Ajax fetch()返回null

时间:2018-04-25 16:46:59

标签: php ajax

所以,我正在做一个琐事游戏。这是我的PHP代码和我的Ajax代码。问题是,无论我做什么,我的PHP代码中的变量$ categoryName都会保持返回null。因此,在我的JS代码中,当我尝试获取url时,我不断收到此错误:“Uncaught(在promise中)SyntaxError:在位置0的JSON中出现意外的令牌     在parse()“

此代码尚未处于完成状态,但此问题阻止我继续前进。有任何想法吗?这是AMPPS服务器上的两个不同文件

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

?>

JavaScript文件

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

    }

1 个答案:

答案 0 :(得分:0)

(我还不能评论,但这是我的看法:) 正如其他人所解释的那样,你有两个对trivia.php的AJAX调用

在第一个(当用户点击“view-all”时)你没有在GET中指定名称

在第二个(当用户点击特定类别时),您在GET中指定名称

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