ajax异步请求服务器入门级实验

前端之家收集整理的这篇文章主要介绍了ajax异步请求服务器入门级实验前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

曾用jquery的集成ajax,现在来学学JavaScript原生的ajax。。。

下面是一个ajax请求服务端一个xml内容的简单实验。。。(来源于JavaScript程序设计)

步骤一:在服务器上,新建一个xml,命名为simpleAjax.xml,输入该文件中的内容是:This is the content of the simpleAjax.xml from server!


步骤二:在服务器上,新建一个html,命名为simpleAjax.html,与刚才建的simpleAjax.xml放在同一个目录下。

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>
  5. simpleAjax
  6. </title>
  7. <script type="text/javascript">
  8. var xmlHttpRequest; //XMLHttpRequest对象名
  9. function sendRequest() { //发送http请求
  10. getXMLHttpRequest(); //获得一个XMLHttpRequest对象到xmlHttpRequest
  11. xmlHttpRequest.onreadystatechange = stateChange; //http状态变化时执行的操作
  12. xmlHttpRequest.open("GET","simpleAjax.xml"); //连接
  13. xmlHttpRequest.send(null); //向服务器发送请求(这里内容为空)
  14. }
  15. function getXMLHttpRequest() {
  16. if(window.ActiveXObject) { //IE类
  17. xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  18. }
  19. else if(window.XMLHttpRequest) { //Chrome类
  20. xmlHttpRequest = new XMLHttpRequest();
  21. }
  22. }
  23. function stateChange() {
  24. if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) { //请求已完成且状态OK
  25. alert(xmlHttpRequest.responseText); //作出的反应
  26. }
  27. }
  28. </script>
  29. </head>
  30. <body>
  31. <form action="#">
  32. <input type="button" value="Send Asynchronous Request" onclick="sendRequest();" />
  33. </form>
  34. </body>
  35. </html>

步骤三:浏览器访问。

Chrome的结果:


IE的结果:




小结:获取XMLHttpRequest对象 ——>> 设置状态改变的动作 ——>> 连接 ——>> 发送请求。

猜你在找的Ajax相关文章