简体   繁体   中英

Ajax isn't fetching the text file

<!DOCTYPE html>

<head>
    <title>
        Ajax Joke of the Dya application
    </title>
    <script>
        var Request = false;
        if (window.XMLHttpRequest) {
            Request = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            Request = new ActiveXObject("Microsoft.XMLHTTP");
        }

        function RetrieveJoke(url, elementID) {
            console.log("Ret")
            if (Request) {
                var RequestObj = document.getElementById(elementID);

                Request.open("GET", url);

                Request.onreadystatechange = function() {
                    if (Request.readystate == 4 && Request.status == 200) {
                        RequestObj.innerHTML = Request.responseText;
                    }
                }
            }
        }
    </script>
</head>

<body>
    <h1> Where do bees go when they get married?</h1>
    <button type="button" value="Fetch Answer" onsubmit="RetrieveJoke('honeymoon.txt','Target')"> ANSWERRR</button>
    <form>
        <input type="button" value="Fetch Answer" onsubmit="retrieveJoke('honeymoon.txt', 'Target')" />

    </form>

    <div id="Target"> </div>
</body>

</html>

so it's a simple joke of the day application to learn ajax wherein the the button is supposed to fetch the answer and we deplo ajax for the same

here is the ajax code that's supposed to fetched "Honeymoon." that's written in honeymoon?txt file when we click on the answer and fetch answer button but it isn't??? Please help

You could just use this function

async function fetchData(path) {
  const data = await fetch(path); // Fetching file content
  return await data.text(); // Converting it to text and return
}

Then call it like this

const data = fetchData("./myfile.txt"); // Pass your file path here
console.log(data); // This will return your file content

So final answer could be

const button = document.querySelector("button"); // Your button
const result = document.querySelector("#Target"); // Your result div

button.addEventListener("click", function() {
  const data = fetchData("./honeymoon.txt");
  result.textContent = data;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM