【问题标题】:Vanilla Javascript version of AJAX [duplicate]AJAX的香草Javascript版本[重复]
【发布时间】:2018-11-19 10:44:37
【问题描述】:

当我只想使用 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>

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

您可以使用fetch 函数。

以下是链接中的示例:

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

【讨论】:

  • 这是作为答案发布的,但它不会尝试回答问题。
  • fetch 是 jquery.ajax 的香草版本,我看不出有什么问题,我做错了什么??
  • 这更好,但您最初的帖子不是答案:提供答案链接实际上并不是在回答问题。
  • 我不知道总得有代码xD,反正谢谢你的解释,我这里比较新
【解决方案2】:

您可以尝试使用 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>

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

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

【讨论】:

    【解决方案3】:

    例如,您可以使用 build in fetch 模块

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

    【讨论】:

    • 记录response 并不是很有用。你宁愿返回 response.text()response.json() 或类似的东西,并在下一个 then 调用中记录。
    • response.text() 和 response.json() 不会显示带有状态码和标题的完整响应对象
    猜你喜欢
    • 2011-11-25
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 2016-08-23
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多