【问题标题】:Ajax Without JQuery? [duplicate]没有 JQuery 的 Ajax? [复制]
【发布时间】:2023-03-20 21:38:02
【问题描述】:

可能重复:
How to make an ajax call without jquery?

如何在不使用 jQuery 的情况下使用 ajax 异步更新网页?

【问题讨论】:

  • 好的,我复制了你之前问题的答案内容。我已将其标记为社区 Wiki,因此我不会从中获得任何代表(不幸的是,你也不会)。请酌情编辑。今后,如果您想立即回答,请在提问时使用回答您自己的问题复选框。

标签: javascript ajax


【解决方案1】:

作为一名年轻的新开发人员,我已经习惯了 JQuery,以至于我对 JavaScript 感到害怕(不像 GetElementById JavaScript,而是面向对象,动态传递函数和闭包是失败和哭泣之间的区别—— with-joy JavaScript)。

我提供这个复制/粘贴的 POST ajax 表单,忽略 Microsoft 的细微差别,用最少的 cmets 帮助像我这样的其他人通过示例学习:

//ajax.js
function myAjax() {
 var xmlHttp = new XMLHttpRequest();
 var url="serverStuff.php";
 var parameters = "first=barack&last=obama";
 xmlHttp.open("POST", url, true);

 //Black magic paragraph
 xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xmlHttp.setRequestHeader("Content-length", parameters.length);
 xmlHttp.setRequestHeader("Connection", "close");

 xmlHttp.onreadystatechange = function() {
  if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
   document.getElementById('ajaxDump').innerHTML+=xmlHttp.responseText+"<br />";
  }
 }

 xmlHttp.send(parameters);
}

这是服务器代码:

<?php
 //serverStuff.php

 $lastName= $_POST['last'];
 $firstName = $_POST['first'];

 //everything echo'd becomes responseText in the JavaScript
 echo "Welcome, " . ucwords($firstName).' '.ucwords($lastName);

?>

和 HTML:

<!--Just doing some ajax over here...-->
<a href="#" onclick="myAjax();return false">Just trying out some Ajax here....</a><br />
<br />
<span id="ajaxDump"></span>

希望有一个可以复制/粘贴的 POST ajax 示例,其他新开发人员将少一个借口来尝试没有 JQuery 训练轮的 JavaScript。

【讨论】:

  • 很高兴我能帮上忙,@user1634617。
  • 旧帖子,但认为这很重要——我对规范的理解是 POST 请求应返回 201 状态代码,因此请确保您在条件内部寻找正确的状态代码onreadystatechange 函数。
【解决方案2】:

熟悉XMLHttpRequest 对象,然后您就可以正确决定使用什么(如果有)JavaScript 框架来处理它。

【讨论】:

    【解决方案3】:

    现在进行 AJAX 调用的最佳方式是使用 JQuery。无论如何,这是来自 W3schools.com 的示例

    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
    function loadXMLDoc()
    {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","ajax_info.txt",true);
    xmlhttp.send();
    }
    </script>
    </head>
    <body>
    
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>
    
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 1970-01-01
      • 2016-05-07
      • 2018-08-30
      • 1970-01-01
      • 2011-11-05
      • 2017-11-03
      • 2010-10-13
      • 2015-08-17
      相关资源
      最近更新 更多