javascript中级--ajax
Posted Mr_W
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript中级--ajax相关的知识,希望对你有一定的参考价值。
一、ajax.js
function ajax(url, fnSucc, fnFaild) { // 1、创建ajax var oAjax = null; if (window.XMLHttpRequest) { var oAjax = new XMLHttpRequest(); } else { var oAjax = new ActiveXObject("Microsoft.XMLHTTP"); } //2 连接服务器 oAjax.open(‘GET‘, url, true); //3发送请求 oAjax.send(); //4接收返回 oAjax.onreadystatechange = function() { if (oAjax.readyState == 4) { //完成 if (oAjax.status == 200) { //成功 fnSucc(oAjax.responseText); } else { if (fnFaild) { fnFaild(); } } } } }
二、实例一--无刷新读取文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ajax</title> <script src="ajax.js"></script> <script> //无刷新数据读取,ajax window.onload = function() { var oBtn = document.getElementById(‘btn1‘) oBtn.onclick = function() { ajax(‘txt1.txt‘, function(str) { alert(str); }) } } </script> </head> <body> 点击后读取txt1.txt<br/> <input id="btn1" type="button" name="" value="读取"> </body> </html>
三、实例二--简单分页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>简单分页</title> <style> #div1 { width: 400px; height: 300px; background: #ccc; border: 1px solid red; } </style> <script src="ajax.js"></script> <script> window.onload = function() { var aBtn = document.getElementsByTagName(‘input‘); var oDiv = document.getElementById(‘div1‘); var i = 0; for (i = 0; i < aBtn.length; i++) { aBtn[i].index = i; aBtn[i].onclick = function() { ajax(this.index + 1 + ‘.txt‘, function(str) { oDiv.innerHTML = str; }) } } } </script> </head> <body> <input type="button" name="" value="按钮1"> <input type="button" name="" value="按钮2"> <input type="button" name="" value="按钮3"> <div id="div1"> </div> </body> </html>
以上是关于javascript中级--ajax的主要内容,如果未能解决你的问题,请参考以下文章
AJAX 响应:数据(JSON、XML)还是 HTML 片段? [关闭]