How do I make a GET request in pure JavaScript?
How can I use javascript to make a GET request and get a response from it (the html code of a certain page)?
For example: site.ru/index.php site.ru/auth.php
You need to go to index.php assign a script to js, so that it would make a get request to auth.php, and got its source code.
I do this:
<script type="text/javascript">
var x = new XMLHttpRequest();
x.open("GET", "http://ya.ru/r=" + Math.random(), true);
x.onreadystatechange = function ()alert(x.responseText);}
x.send(null);
</script>
But it opens an empty alert.
3
1 answers
On pure JS, everything will work out. You have a typo: you missed the" {". And you need to catch the event load
instead of onreadystatechange
:
var x = new XMLHttpRequest();
x.open("GET", "/echo/json/", true);
x.onload = function (){
alert( x.responseText);
}
x.send(null);
Well, take an interest in cross-domain queries - "you can't just take it and" turn to a different site than the one from which the script is sent.
13
Author: Sergiks, 2014-02-24 17:29:42