HTTP GET request in JavaScript?
Muszę wykonać HTTP GET request w JavaScript. Jak najlepiej to zrobić?
Muszę to zrobić w widgecie Mac OS X dashcode.
27 answers
Przeglądarki (i Dashcode) dostarczają obiekt XMLHttpRequest, który może być użyty do wysyłania żądań HTTP z JavaScript:
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
Jednak żądania synchroniczne są zniechęcane i generują ostrzeżenie w następujący sposób:
Uwaga: począwszy od Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchroniczne żądania w głównym wątku zostały wycofane ze względu na negatywny wpływ na doświadczenie użytkownika.
Powinieneś zrobić asynchroniczne żądanie i obsługa odpowiedzi wewnątrz procedury obsługi zdarzenia.
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-03 15:43:08
W jQuery :
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-24 15:42:26
Wiele świetnych porad powyżej, ale niezbyt wielokrotnego użytku i zbyt często wypełnionych nonsensami DOM i innymi puszkami, które ukrywają łatwy kod.
Oto Klasa Javascript, którą stworzyliśmy, która jest wielokrotnego użytku i łatwa w użyciu. Obecnie ma tylko metodę GET, ale to działa dla nas. Dodawanie postu nie powinno obciążać niczyich umiejętności.
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
Korzystanie z niego jest tak proste jak:
var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
// do something with response
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-14 20:17:08
Nowy window.fetch
API jest czystszym zamiennikiem XMLHttpRequest
, który wykorzystuje obietnice ES6. Jest ładne Wyjaśnienie tutaj , ale sprowadza się to do (Z artykułu):
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function() {
console.log("Booo");
});
Obsługa przeglądarki jest teraz dobra w najnowszych wersjach (działa w Chrome, Firefox, Edge (v14), Safari (v10.1), Opera, Safari iOS (v10.3), przeglądarka Android i Chrome dla Androida), jednak IE prawdopodobnie nie otrzyma oficjalnego wsparcia. GitHub ma Dostępny polyfill, który jest zalecane do obsługi starszych przeglądarek nadal w dużej mierze używanych(wersje ESP Safari sprzed marca 2017 i przeglądarki mobilne z tego samego okresu).
Domyślam się, czy jest to wygodniejsze niż jQuery czy XMLHttpRequest, czy też nie zależy od charakteru projektu.
Oto link do spec https://fetch.spec.whatwg.org/
Edit :
Using ES7 async / wait, this becomes simply (based on this Gist):
async function fetchAsync (url) {
let response = await fetch(url);
let data = await response.json();
return data;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-20 22:58:07
Wersja bez wywołania zwrotnego
var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-11-08 09:50:21
Oto kod do zrobienia tego bezpośrednio z JavaScript. Ale, jak wcześniej wspomniano, byłoby znacznie lepiej z biblioteki JavaScript. Moim ulubionym jest jQuery.
W poniższym przypadku, strona ASPX (która jest serwisowana jako usługa odpoczynku biednego człowieka) jest wywoływana, aby zwrócić obiekt JavaScript JSON.
var xmlHttp = null;
function GetCustomerInfo()
{
var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open( "GET", Url, true );
xmlHttp.send( null );
}
function ProcessRequest()
{
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
if ( xmlHttp.responseText == "Not found" )
{
document.getElementById( "TextBoxCustomerName" ).value = "Not found";
document.getElementById( "TextBoxCustomerAddress" ).value = "";
}
else
{
var info = eval ( "(" + xmlHttp.responseText + ")" );
// No parsing necessary with JSON!
document.getElementById( "TextBoxCustomerName" ).value = info.jsonData[ 0 ].cmname;
document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-16 08:33:12
A copy-paste modern version ( using fetch and arrow function ) :
//Option with catch
fetch( textURL )
.then(async r=> console.log(await r.text()))
.catch(e=>console.error('Boo...' + e));
//No fear...
(async () =>
console.log(
(await (await fetch( jsonURL )).json())
)
)();
A copy-paste classic version:
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
document.body.className = 'ok';
console.log(this.responseText);
} else if (this.response == null && this.status === 0) {
document.body.className = 'error offline';
console.log("The computer appears to be offline.");
} else {
document.body.className = 'error';
}
}
};
request.open("GET", url, true);
request.send(null);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-15 18:01:49
Krótkie i czyste:
const http = new XMLHttpRequest()
http.open("GET", "https://api.lyrics.ovh/v1/toto/africa")
http.send()
http.onload = () => console.log(http.responseText)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-15 15:18:47
IE buforuje adresy URL, aby przyspieszyć ładowanie, ale jeśli, powiedzmy, odpytywasz serwer w odstępach czasu, próbując uzyskać nowe informacje, IE buforuje ten adres URL i prawdopodobnie zwróci ten sam zestaw danych, który zawsze miałeś.
Niezależnie od tego, w jaki sposób skończy się twoje żądanie GET - vanilla JavaScript, Prototype, jQuery itp. - upewnij się, że wprowadziłeś mechanizm do walki z buforowaniem. Aby temu przeciwdziałać, dodaj unikalny token do końca adresu URL, na który chcesz trafić. To można wykonać przez:
var sURL = '/your/url.html?' + (new Date()).getTime();
Spowoduje to dodanie unikalnego znacznika czasu na końcu adresu URL i zapobiegnie buforowaniu.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-12 01:01:08
Prototype makes it dead simple
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-29 16:35:26
Jedno rozwiązanie obsługujące starsze przeglądarki:
function httpRequest() {
var ajax = null,
response = null,
self = this;
this.method = null;
this.url = null;
this.async = true;
this.data = null;
this.send = function() {
ajax.open(this.method, this.url, this.asnyc);
ajax.send(this.data);
};
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch(e) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
}
catch(error) {
self.fail("not supported");
}
}
}
if(ajax == null) {
return false;
}
ajax.onreadystatechange = function() {
if(this.readyState == 4) {
if(this.status == 200) {
self.success(this.responseText);
}
else {
self.fail(this.status + " - " + this.statusText);
}
}
};
}
Może trochę przesadziłeś, ale z tym kodem na pewno będziesz bezpieczny.
Sposób użycia:
//create request with its porperties
var request = new httpRequest();
request.method = "GET";
request.url = "https://example.com/api?parameter=value";
//create callback for success containing the response
request.success = function(response) {
console.log(response);
};
//and a fail callback containing the error
request.fail = function(error) {
console.log(error);
};
//and finally send it away
request.send();
Nie jestem zaznajomiony z widgetami Dashcode systemu Mac OS, ale jeśli pozwolą Ci korzystać z bibliotek JavaScript i wspierać XMLHttpRequests , użyłbym jQuery i zrobił coś takiego:
var page_content;
$.get( "somepage.php", function(data){
page_content = data;
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-27 14:27:03
Nowoczesne, czyste i najkrótsze
fetch('https://www.randomtext.me/api/lorem')
let url = 'https://www.randomtext.me/api/lorem';
// to only send GET request without waiting for response just call
fetch(url);
// to wait for results use 'then'
fetch(url).then(r=> r.json().then(j=> console.log('\nREQUEST 2',j)));
// or async/await
(async()=>
console.log('\nREQUEST 3', await(await fetch(url)).json())
)();
Open Chrome console network tab to see request
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-09-07 12:00:35
Aby to zrobić, API pobierania jest zalecanym podejściem, przy użyciu obietnic JavaScript. XMLHttpRequest (XHR), IFrame object lub dynamic tags są starszymi (i bardziej clunkiernymi) podejściami.
<script type=“text/javascript”>
// Create request object
var request = new Request('https://example.com/api/...',
{ method: 'POST',
body: {'name': 'Klaus'},
headers: new Headers({ 'Content-Type': 'application/json' })
});
// Now use it!
fetch(request)
.then(resp => {
// handle response })
.catch(err => {
// handle errors
}); </script>
Oto wielki pobierz demo i MDN docs
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-17 22:52:56
W Informacji Twojego widgetu.plik plist, nie zapomnij ustawić klucza AllowNetworkAccess
Na true.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-29 19:42:10
Najlepszym sposobem jest korzystanie z AJAX ( prosty samouczek znajdziesz na tej stronie Tizag ). Powodem jest to, że każda inna technika, której możesz użyć, wymaga więcej kodu, nie jest gwarantowana praca między przeglądarkami bez przeróbek i wymaga użycia większej ilości pamięci klienta poprzez otwieranie ukrytych stron wewnątrz ramek przekazujących adresy URL Przetwarzające ich Dane i zamykające je. AJAX jest sposobem, aby przejść w tej sytuacji. Że moje dwa lata ciężkiego rozwoju javascript mówi.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-29 23:01:11
Dla tych, którzy używają AngularJs , to $http.get
:
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-06 20:36:35
Żądanie GET HTTP można uzyskać na dwa sposoby:
-
To podejście oparte na formacie xml. Musisz podać adres URL żądania.
xmlhttp.open("GET","URL",true); xmlhttp.send();
-
Ten jest oparty na jQuery. Musisz podać adres URL i nazwę funkcji, którą chcesz wywołać.
$("btn").click(function() { $.ajax({url: "demo_test.txt", success: function_name(result) { $("#innerdiv").html(result); }}); });
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-03 17:11:34
function get(path) {
var form = document.createElement("form");
form.setAttribute("method", "get");
form.setAttribute("action", path);
document.body.appendChild(form);
form.submit();
}
get('/my/url/')
To samo można zrobić również dla żądania post.
Spójrz na ten link JavaScript POST request like a form submit
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:26
Proste żądanie asynchroniczne:
function get(url, callback) {
var getRequest = new XMLHttpRequest();
getRequest.open("get", url, true);
getRequest.addEventListener("readystatechange", function() {
if (getRequest.readyState === 4 && getRequest.status === 200) {
callback(getRequest.responseText);
}
});
getRequest.send();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-18 18:40:56
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-27 13:52:30
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'restUrl', true)
request.onload = function () {
// Begin accessing JSON data here
}
// Send request
request.send()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-05 06:00:18
Jeśli chcesz użyć kodu dla widżetu pulpitu nawigacyjnego, a nie chcesz dołączać biblioteki JavaScript do każdego utworzonego widżetu, możesz użyć obiektu XMLHttpRequest, który jest natywnie obsługiwany przez Safari.
Jak donosi Andrew Hedges, widżet domyślnie nie ma dostępu do sieci; musisz zmienić to ustawienie w informacji.plist związany z widżetem.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-07 05:03:15
Aby odświeżyć najlepszą odpowiedź od joann z obietnicą to jest mój kod:
let httpRequestAsync = (method, url) => {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (xhr.status == 200) {
resolve(xhr.responseText);
}
else {
reject(new Error(xhr.responseText));
}
};
xhr.send();
});
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-27 14:01:16
Możesz to zrobić z czystym JS też:
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Make the actual CORS request.
function makeCorsRequest() {
// This is a sample server that supports CORS.
var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
Zobacz: po więcej szczegółów: html5rocks tutorial
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-21 11:18:54
<button type="button" onclick="loadXMLDoc()"> GET CONTENT</button>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
var url = "<Enter URL>";``
xmlhttp.onload = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == "200") {
document.getElementById("demo").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-06 06:06:39
Oto alternatywa dla plików xml, aby załadować pliki jako obiekt i uzyskać dostęp do właściwości jako obiekt w bardzo szybki sposób.
- Uwaga, Aby javascript mógł go i poprawnie zinterpretować zawartość konieczne jest zapisanie plików w tym samym formacie, co strona HTML. Jeśli używasz UTF 8 Zapisz swoje pliki w UTF8 itp.
XML działa jako drzewo ok? zamiast pisać
<property> value <property>
Napisz prosty plik w ten sposób:
Property1: value
Property2: value
etc.
Zapisz swój plik .. Teraz zadzwoń funkcja ....
var objectfile = {};
function getfilecontent(url){
var cli = new XMLHttpRequest();
cli.onload = function(){
if((this.status == 200 || this.status == 0) && this.responseText != null) {
var r = this.responseText;
var b=(r.indexOf('\n')?'\n':r.indexOf('\r')?'\r':'');
if(b.length){
if(b=='\n'){var j=r.toString().replace(/\r/gi,'');}else{var j=r.toString().replace(/\n/gi,'');}
r=j.split(b);
r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});
r = r.map(f => f.trim());
}
if(r.length > 0){
for(var i=0; i<r.length; i++){
var m = r[i].split(':');
if(m.length>1){
var mname = m[0];
var n = m.shift();
var ivalue = m.join(':');
objectfile[mname]=ivalue;
}
}
}
}
}
cli.open("GET", url);
cli.send();
}
Teraz możesz efektywnie uzyskać swoje wartości.
getfilecontent('mesite.com/mefile.txt');
window.onload = function(){
if(objectfile !== null){
alert (objectfile.property1.value);
}
}
To tylko mały prezent dla grupy. Dzięki za tak:)
Jeśli chcesz przetestować tę funkcję na komputerze lokalnie, uruchom ponownie przeglądarkę za pomocą następującego polecenia (obsługiwane przez wszystkie przeglądarki z wyjątkiem safari):
yournavigator.exe '' --allow-file-access-from-files
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-15 10:52:56