原生 Javascript 版本的 AJAX

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50776445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:16:06  来源:igfitidea点击:

Vanilla Javascript version of AJAX

javascriptjqueryajax

提问by John

How can I remove the need to download a full jquery library when all I want to use is AJAX. Is there a smaller file that focuses on AJAX or is there a Vanilla Javascript version of this code?

当我只想使用 AJAX 时,如何消除下载完整 jquery 库的需要。是否有专注于 AJAX 的较小文件,或者是否有此代码的 Vanilla Javascript 版本?

<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){

            $.ajax({
                type: 'POST',
                url: 'cookies.php',
                success: function(data) {
                    alert(data);
                }
            });
   });
});
</script>

采纳答案by Always Sunny

You can try with XMLHttpRequestlike below.

您可以尝试使用如下所示的XMLHttpRequest

<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {

   var xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
       }
     };

   xhttp.open("POST", "cookies.php", true);
   xhttp.send();
}
</script>

</body>
</html>

Demo:https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_first

演示:https : //www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_first

Reference:https://www.w3schools.com/js/js_ajax_http_send.asp

参考:https : //www.w3schools.com/js/js_ajax_http_send.asp

回答by Gustavo Topete

You can use the fetchfunction.

您可以使用该fetch功能。

Here is an example from the link:

这是链接中的一个示例:

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

回答by Always Sunny

you can use build in fetch module for example

例如,您可以使用内置 fetch 模块

fetch('http://yourapi.com/data')
  .then(response => {
    console.log(response)
  });