javascript——使用ajax

创建XMLHttpRequest

IE5:request = new ActiveXObject(“Microsoft.XMLHTTP”)

ie6+: request = new ActiveXObject(“Msxml2.XMLHTTP”)

其他浏览器: request = new XMLHttpRequest()

 

 

1.属性

onreadystatechage

readyState

responseText

responseXML

status

statusText

 

 

2.方法

abort()

getAllResponseHeaders()

getResponseHeader(param)

open(‘method’,’url’,’asynch’)

send(data)

setRequestHeader(‘param’,’value’)

 

 

 

3.用post方法的ajax程序

<script>

params = “url=amazon.com/gp/aw”              //url和amazon.com/gp/aw在后面的send()函数发送后,会作为post的键值对,即$_POST[‘url’] = “amazon.com/gp/aw”

request = new ajaxRequest()

request.open(“POST”,”urlpost.php”,true)

request.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”)

request.setRequestHeader(“Content-length”,params.length)

request.setRequestHeader(“Connection”,”close”)

request.onreadystatechange = function(){

if (this.readyState == 4){

if (this.status == 200){

if (this.responseText != null){

document.getElementById(‘info’).innerHTML = this.responseText

}

else alert(“Ajax error: No data received”)

}

else alert(“Ajax error: ” + this.statusText)

}

}

request.send(params)                                 //发送了post的键值对

 

function ajaxRequest(){

try{

var request = new XMLHttpRequest()

}

catch(e1){

try{

request = new ActiveXObject(“Msxml2.XMLHTTP”)

}

catch(e2){

try{

request = new ActiveXObject(“Msxml2.XMLHTTP”)

}

catch(e3){

request = false

}

}

}

return request

}

 

</script>

 

 

 

 

4.用get方法

相比较post,get方法有三个地方需要改动

第一个,不需要发送标题

request.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”)

request.setRequestHeader(“Content-length”,params.length)

request.setRequestHeader(“Connection”,”close”)

不需要

 

第二,get的参数键值对不需要通过send()函数发送

nocache = “&nochache=” + Math.random() * 10000000                            //&标记开始第二个参数/值对,这样可以确保每个url不同,从而不会被隐藏

request.open(“GET”,”urlget.php?url=amazon.com/gp/aw” + noncache,true)   //?提供get方法的参数/值对

 

 

send(null)   //send()函数不需要发送参数,但不能舍弃这个函数

 

第三,php程序中改为$_GET[‘url’]

Add a Comment

电子邮件地址不会被公开。 必填项已用*标注