AJAX 的基本框架

前端之家收集整理的这篇文章主要介绍了AJAX 的基本框架前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1.  
  1. //创建XMLHttpRequest对象
  1. function getXMLHttpRequest()
  2. {
  3. http_request = false;
  4. if(window.XMLHttpRequest)
  5. {
  6. http_request = new XMLHttpRequest();
  7. if(http_request.overrideMimeType)
  8. http_request.overrideMimeType("text/xml");
  9. }
  10. else
  11. {
  12. if(window.ActiveXObject)
  13. {
  14. try
  15. {
  16. http_request = new ActiveXObject("Msxml2.XMLHTTP");
  17. }
  18. catch(e)
  19. {
  20. try
  21. {
  22. http_request = new ActiveXObject("Microsoft.XMLHTTP");
  23. }catch(e)
  24. {
  25. }
  26. }
  27. }
  28. }
  29. return http_request;
  30. }
  31. //发送请求
  32. /*
  33. @http_request 异步请求对象
  34. @url 请求位置
  35. @method 请求方法
  36. @content 请求内容 eg. param1=xxx1¶m2=xxx2
  37. @callBack 请求回调
  38. */
  39. function send_request(http_request,url,method,content,callBack)
  40. {
  41. if(!http_request)
  42. {
  43. alert('无法创建异步请求对象!');
  44. return;
  45. }
  46. http_request.onreadystatechange = callBack;
  47. if(method.toUpperCase() == 'GET')
  48. {
  49. http_request.open(method,true);
  50. http_request.setRequestHeader('Content-Type','text/html;charset=UTF-8');
  51. }
  52. else if(method.toUpperCase == 'POST')
  53. {
  54. http_request.open(method,'application/x-www-form-urlencoded');
  55. }
  56. else
  57. {
  58. alert('请求方法出错!');
  59. return;
  60. }
  61. http_request.send(content);
  62. }
  63. //返回文本的
  64. function getWebContent()
  65. {
  66. var webConReq = getXMLHttpRequest();//ajax不支持跨跨域访问
  67. send_request(webConReq,'./servlet/testServlet','get',null,function()
  68. {
  69. if(webConReq.readyState == 4)
  70. {
  71. if(webConReq.status == 200)
  72. {
  73. var doc = webConReq.responseText;
  74. if(doc)
  75. {
  76. document.getElementById("pageCon").innerHTML = doc;
  77. }
  78. }
  79. else
  80. {
  81. alert('请求失败!');
  82. }
  83. }
  84. }
  85. );
  86. }
  87. //返回xml
  88. function getXml()
  89. {
  90. var webConReq = getXMLHttpRequest();//ajax不支持跨跨域访问
  91. send_request(webConReq,'./NewFile.xml',function()
  92. {
  93. if(webConReq.readyState == 4)
  94. {
  95. if(webConReq.status == 200)
  96. {
  97. var doc = webConReq.responseXML;
  98. if(doc)
  99. {
  100. var root = doc.getElementsByTagName("items")[0];
  101. var items = root.getElementsByTagName("item");
  102. var html = '';
  103. for(var i=0;i<items.length;i++)
  104. {
  105. html += "id:" + items[i].getAttribute('id');
  106. html += " name:" + items[i].getAttribute('name');
  107. }
  108. document.getElementById("xml").innerHTML = html;
  109. }
  110. }
  111. else
  112. {
  113. alert('请求失败!');
  114. }
  115. }
  116. }
  117. );
  118. }
  119.  
  120. <a href="javascript:getWebContent();">异步获取页面</a>
  121. <font id="pageCon"></font><br>
  122. <a href="javascript:getXml();">异步XML</a>
  123. <font id="xml"></font>

猜你在找的Ajax相关文章