繁体   English   中英

在 vanilla JavaScript 中向服务器发送 GET 请求的最佳方式是什么?

[英]What is the best way to send a GET request to the server in vanilla JavaScript?

在 vanilla JavaScript 中向服务器发送 GET 请求的最佳方式是什么?

在 vanilla javascript 中,您可以使用fetch API

fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(myJson);
  });

您可以进行重定向以执行同步 GET 请求:

var url = 'http://domain/path/?var1=&var2=';

window.location = url;

使用XMLHttpRequest (XHR) 对象。

代码示例:

const http = new XMLHttpRequest();
const url='/test';
http.open("GET", url);
http.send();

http.onreadystatechange = (e) => {
  console.log('done')
}
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", THE_URL, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;

您可以尝试使用 Fetch

 function request() { fetch('http://example.com/movies.json') .then(function(response) { console.log(response.json()) }) .then(function(myJson) { console.log(myJson); }); } request()

我不确定我们是否可以在这里声称是“最佳方式”,但您可以使用

XMLHttpRequest

或者如果你想使用图书馆

阿克西奥斯

如果你安装了 PHP,你可以使用 get_file_content var

 <html>
<script>
var date= "<?php 
echo(file_get_contents('https://apizmanim.com/twilio/zipapi.php?11211?2021/05/14')?>";
document.write(date);
</script>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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