AJAX简单应用
AJAX全称是Asynchronous JavaScript and XML,是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术,而传统的网页如果需要更新内容,必需重新加载整个页面。 1、创建对象 2、向服务器发送请求
GET与POST区别:
send(string) 将请求发送到服务器,string仅用于POST请求。 示例程序一:GET请求 xmlhttp.open("GET","/cgi-bin/test.cgi?para=test&var='123'",true); xmlhttp.send(); 示例程序二:POST请求 xmlhttp.open("POST",true); xmlhttp.send(); 如果需要向HTML表单那样POST数据,请使用setRequestHeader()来添加HTTP头。 xmlhttp.open("POST",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send(); 3、服务器响应 4、readyState状态
示例程序: xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4 && xmlhttp.status==200) { //返回后需要执行的任务 } } 5、AJAX完整示例
<html><!DOCTYPE html> <head> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("POST",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>使用 AJAX 修改该文本内容</h2></div> <button type="button" onclick="loadXMLDoc()">修改内容</button> </body> </html> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |