Ajax基础

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}


open(method,url,async);
send(string);

Method Description
open(method,url,async) Specifies the type of request, the URL, and if the request should be handled asynchronously or not.

method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string) Sends the request off to the server.

string: Only used for POST requests


GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

[b]A cached file is not an option (update a file or database on the server)[/b]
[b]Sending a large amount of data to the server (POST has no size limitations)[/b]
[b]Sending user input (which can contain unknown characters), POST is more robust and secure than GET[/b]


Method Description
setRequestHeader(header,value) Adds HTTP headers to the request.

header: specifies the header name
value: specifies the header value

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");



Server Response

To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.

Property Description
responseText get the response data as a string
responseXML get the response data as XML data


[b]The responseText Property[/b]

If the response from the server is not XML, use the responseText property.

The responseText property returns the response as a string, and you can use it accordingly:

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;


[b]The responseXML Property[/b]

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
}
document.getElementById("myDiv").innerHTML=txt;

[b]
The onreadystatechange event[/b]


[b]onreadystatechange[/b] Stores a function (or the name of a function) to be called automatically each time the readyState property changes

[b]readyState[/b] Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

[b]status [/b]
200: "OK"
404: Page not found

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值