简体   繁体   中英

How to update url via javascript in the XMLHTTPRequest

I'm trying to update the URL inside my javascript function eg

http://tmaserv.scem.uws.edu.au/chapters/?n=0
http://tmaserv.scem.uws.edu.au/chapters/?n=1

and so on.
I've tried using a for loop but it hasn't work.

Javascript:

function do_exercise () {
    var x = new XMLHttpRequest();{
        x.open('GET', 'http://tmaserv.scem.uws.edu.au/chapters/?n=0', true);
        x.onreadystatechange = function() {
            if (x.readyState == 4 && x.status ==200) {
                obj = (x.responseText);
                JSON.parse(x.responseText);
                obj = JSON.parse(obj);
                document.getElementById("section1").innerHTML =
            obj.data
            }
        }
        x.send(null);
    }
}

HTML:

<nav>           
    <button onclick="do_exercise();">Next section</button>      
</nav>
<section id = "section1">
    <h1>Heading One</h1>
    <p>Paragraph One.</p>
</section>

You could do something like this:

var requestNum = 0;

function do_exercise () {
    var x = new XMLHttpRequest();
    // adjust the GET URL to reflect the new n value and request as before
    x.open('GET', 'http://tmaserv.scem.uws.edu.au/chapters/?n=' + requestNum, true);
    x.onreadystatechange = function() {
        if (x.readyState == 4 && x.status ==200) {
            obj = (x.responseText);
            JSON.parse(x.responseText);
            obj = JSON.parse(obj);
            document.getElementById("section1").innerHTML = obj.data;
            requestNum++;
        }
    }

    x.send(null);
}

Does that make sense? Note that I have removed some curly braces that I presume were a mistake on this line var x = new XMLHttpRequest();{ .

I would also recommend using jQuery.getJSON for your AJAX call for better browser compatibility and cleaner code.

EDIT: Made my answer far simpler. Thanks to Robert for pointing out where I was completely overthinking things!

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