AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
- GET请求
1.一个简单的get请求:<!DOCTYPE html> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=utf8" /> <script> var loadXMLDoc = function() { var xmlhttp; if (window.XMLHttpRequest) { // for IE7+,Ff,Chrome,... xmlhttp = new XMLHttpRequest(); // 创建XMLHttpRequest对象 } else { alert("不为老古董浏览器提供支持-.-") } xmlhttp.onreadystatechange=function() // 为XMLHttpRequest对象的onreadystatechange添加回调函数 { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/ajax/demo_test_get1",true); // open(method,url,async) async:true异步/false(同步) xmlhttp.send(); // 仅仅在POST方式时,send带有参数 } </script> </head> <body> <h2>AJAX</h2> <button type="button" onclick="loadXMLDoc()">请求数据</button> <div id="myDiv"></div> </body> </html>
2.为了避免得到的结果是缓存中的,可以向URL中添加唯一ID:
// open改为: xmlhttp.open("GET","/ajax/demo_test_get2?t=" + Date().getTime(),true);
3.如果您希望通过 GET 方法发送信息,可以向open的URL 添加url参数
// open改为 xmlhttp.open("GET","/ajax/demo_test_get3?fname=Bill&lname=Gates",true);
- POST请求并发送数据
<!DOCTYPE html> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=utf8" /> <script> var loadXMLDoc = function() { var xmlhttp; if (window.XMLHttpRequest) { // for IE7+,... xmlhttp = new XMLHttpRequest(); // 创建XMLHttpRequest对象 } else { alert("不为老古董浏览器提供支持-.-") } xmlhttp.onreadystatechange=function() // 为XMLHttpRequest对象的onreadystatechange添加回调函数 { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.open("POST","/ajax/demo_test_post1",async) async:true异步/false(同步) xmlhttp.send("fname=Bill&lname=Gates");; // 仅仅在POST方式时,send带有参数 } </script> </head> <body> <h2>AJAX</h2> <button type="button" onclick="loadXMLDoc()">请求数据</button> <div id="myDiv"></div> </body> </html>
上面同时也是javascript GET和POST的方式
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。