简体   繁体   中英

Storing the result of a JQuery GET request as a javascript variable

I am trying to use JQuery and JS to take a html filename/URL and return all the text from that file (not including tags).

I have never used JQuery before, and can't work out why my code does not work.

I am using a HTML form to take the filename.

When the form is submitted, it triggers a JS function that should retrieve the text from the provided filename, and store it as a variable.

The First snippet of code is my JS file. The Second is the HTML page that has the form. The Third is a test page.

var pageWords;

function showWords() {
    var filename = $('#filename');
    $.get(filename, function (data) {
        pageWords = data;
        //alert(pageWords)
    });
}






<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Word Count Page</title>
    <script src="JQUERY.js"></script>
    <script src="wordCount.js"></script>
</head>
<body>
<div id="inputContainer">
    <form>
        Enter a file name to be evaluated:
        <input type="text" id="filename">
        <input type="submit" id="submit" onsubmit="showWords()">
    </form>
</div>
<div id="results">

</div>
</body>
</html>






<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test file</title>
</head>
<body>
<b>Some text</b>
    Some more
<small>small text</small>
</body>
</html>

Your code is almost right, but you are passing the input element, not the input value, to jQuery.
Also, your <form> will be submitted as soon as the user clicks on the submit button, probably redirecting the user to another page and discarding all form data.

The following may fix those problems.

var pageWords;

function showWords() {
    // var filename = $('#filename'); // `filename` is an object
    var filename = $('#filename').val(); // `val()` returns the content of the input
    $.get(filename, function (data) {
        pageWords = data;
        //alert(pageWords)
    });
}

// Remember to abort the default submit action
var form = document.querySelector('form')
form.addEventListener('submit', event => event.preventDefault())

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-2024 STACKOOM.COM