终于学到Ajax以前一直没接触到一直以为很NB,对这些内容我基本上是个小白中的小白哎,继续加油
Ajax可以做到只更新页面的一下部分,其他部分不需要重新加载
下面就是根据书上的内容所写
HTML
<div id="new"></div>
js
addLoadEvent
function addLoadEvent(func){
var oldonload = window.onload;
if(typeof window.onload != "function" ){
window.onload = func;
}else{
window.onload = function(){
oldonload();
func();
}
}
}
getHTTPObject
function getHTTPObject(){
if(typeof XMLHttpRequest == "undefined")
XMLhttpRequest = function(){
try{
return new ActiveXObject("Msml2.XMLHTTP.6.0");
}catch(e){}
try{
return new ActiveXObject("Msml2.XMLHTTP.3.0");
}catch(e){}
try{
return new ActiveXObject("Msml2.XMLHTTP");
}catch(e){}
return false;//如果浏览器不支持XMLHttpRequest就会返回false
}
return new XMLHttpRequest();
}
getNewContent
function getNewContent(){
var request = getHttpObject();//创建request对象
if(request){
request.open("GET","example.txt",true);//get类型、url、是否异步
request.onreadystatechange = function(){//服务器返回响应时触发
/*
function要在onreadystatechange被触发时执行,而不是立即执行,所以不要加()
request.onreadystatechange = doSomething;相当于是在传递指针而不是在加(),是在传递最后函数的值
*/
if(request.readyState == 4){//返回的类型
/*
readystate == 0 :未初始化
readystate == 1 :正在加载
readystate == 2 :加载成功
readystate == 3 :正在交互
readystate == 4 :完成
*/
if(request.status == 200){ //判断是否一切准备就绪
var para = document.createElement("p");
var txt = document.createTextNode(request.responseText);
para.appendChild(txt);
document.getElementById("new").appendChild(para);
//document.getElementById("new").innerHTML = request.responseText;
}
}
};
request.send();//发送请求GET请求
//request.send(需要传的数据);发送请求POST请求
}else{
alert("Sorry,your browser dosen\'t support XMLHttpRequest !!!");
}
}
addLoadEvent(getNewContent);
在写这个是时候我出现了以下问题
注意:有些浏览器会限制Ajax请求使用的协议(Firefox可以)其他的浏览器要搭建服务器localhost,或在网址加空格–allow-file-access-from-files
扩展(以后应该要不断更新)
GET的请求
request.open("GET", "test1.txt", true);
request.send();
POST的请求
request.open("POST", "ajax_test.asp", true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("fname=Bill&lname=Gates");
属性
request.open(METHOD, URL, ASYNC);
METHOD: 请求类型 GET, POST
URL: 目标链接地址,包括 QueryString
ASYNC: 是否异步请求
send(请求内容)