Ajax快速入门
什么是AJAX?AJAX的意思就是异步的JavaScript和XML。简而言之,它是使用XMLHttpRequest对象与服务器端通信的脚本语言。它可以发送及接收各种格式的信息,包括JSON、XML、HTML和文本文件。AJAX最为吸引人的就是它的“异步”特性,这意味着AJAX可以无需刷新页面而与服务器端进行通信。允许你根据用户事件来更新部分页面内容。 可以考虑的两个特性:
第一步:如何发送一个HTTP请求需要通过XMLHttpRequest实现使用JavaScript向服务器端发送一个HTTP请求。而Internet Explorer(IE)中引入一个名为XMLHTTP的ActiveX对象实现与XMLHttpRequest相同的功能,Mozilla、Safari和其他浏览器则使用XMLHttpRequest。 如果要兼容各个浏览器的话,可以这样来做: var httpRequest;
if (window.XMLHttpRequest) { // Mozilla,Safari,IE7+ ...
? ?httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
? ?httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
接下来,当接收到服务器端响应时,需要告诉HTTP请求对象使用JavaScript函数来处理响应。将XMLHttpRequest对象的onreadystatechange属性设置为该函数的名称,当请求的状态变化时,该函数会被调用。 httpRequest.onreadystatechange = nameOfTheFunction;
注意:该函数名没有传递参数的括号和参数,这表示只是分配了一个函数的引用,而不是真正调用该函数。当然,也可以动态定义一个匿名函数,这样可以实时地处理响应。 httpRequest.onreadystatechange = function(){
? ?// process the server response
};
在处理完服务器端的响应之后,我们就可以调用XMLHttpRequest对象的open()和send()方法向服务器端发送请求了。 httpRequest.open('GET','http://www.example.org/some.file',true);
httpRequest.send(null);
send()方法的参数表示当请求为POST时,向服务器端发送请求的数据内容。如果发送的是表单数据格式的话,服务器端可以向字符串一样地解析。 "name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
向服务器端发送的数据格式也可以是JSON、SOAP等格式。 注意:如果使用POST方式发送数据的话,在调用send()方法前,需要设置请求的MIME类型。: httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
第二步:处理服务器端的响应当发送请求时,已经定义了一个函数来处理响应。 httpRequest.onreadystatechange = nameOfTheFunction;
这个函数可以做什么呢?首先,该函数需要检查请求的状态。如果状态值为4的话,这表示接收到完成的服务器端响应,可以继续处理。 if (httpRequest.readyState === 4) {
? ?// everything is good,the response is received
} else {
? ?// still not ready
}
readyState的值列表如下:
接下来需要检查HTTP服务器端响应的状态代码,W3C网站 列出了所有的状态代码。下面的例子中,通过是否为200 OK的状态码来判断AJAX调用是否是成功的。 if (httpRequest.status === 200) {
? ?// perfect!
} else {
? ?// there was a problem with the request,? ?// for example the response may contain a 404 (Not Found)
? ?// or 500 (Internal Server Error) response code
}
在检查了请求的状态和响应的状态码后,就可以接收服务器端发送的数据并处理。有两种选项访问这些数据:
注意,上述步骤只有异步请求(open()方法的第三个参数设置为true)时才是有效的。如果使用同步请求的话,是不需要指定函数的。在调用send()方法后就可以访问到服务器端返回的数据,因为脚本会停止并等待服务器端的响应。 第三步:一个简单的例子下面来做一个简单的HTTP请求。JavaScript将请求一个包含“I’m a test.”文本的“test.html”HTML文档,然后使用alert()方法打印test.html文件的内容。 <span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
?Make a request
</span>
<script type="text/javascript">
(function() {
?var httpRequest;
?document.getElementById("ajaxButton").onclick = function() { makeRequest('test.html'); };
?function makeRequest(url) {
? ?if (window.XMLHttpRequest) { // Mozilla,...
? ? ?httpRequest = new XMLHttpRequest();
? ?} else if (window.ActiveXObject) { // IE
? ? ?try {
? ? ? ?httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
? ? ?}
? ? ?catch (e) {
? ? ? ?try {
? ? ? ? ?httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
? ? ? ?}
? ? ? ?catch (e) {}
? ? ?}
? ?}
? ?if (!httpRequest) {
? ? ?alert('Giving up :( Cannot create an XMLHTTP instance');
? ? ?return false;
? ?}
? ?httpRequest.onreadystatechange = alertContents;
? ?httpRequest.open('GET',url);
? ?httpRequest.send();
?}
?function alertContents() {
? ?if (httpRequest.readyState === 4) {
? ? ?if (httpRequest.status === 200) {
? ? ? ?alert(httpRequest.responseText);
? ? ?} else {
? ? ? ?alert('There was a problem with the request.');
? ? ?}
? ?}
?}
})();
</script>
在这个例子中:
function alertContents() {
?try {
? ?if (httpRequest.readyState === 4) {
? ? ?if (httpRequest.status === 200) {
? ? ? ?alert(httpRequest.responseText);
? ? ?} else {
? ? ? ?alert('There was a problem with the request.');
? ? ?}
? ?}
?}
?catch( e ) {
? ?alert('Caught Exception: ' + e.description);
?}
}
第四步:使用XML进行响应在前面的例子中,当接收到响应后使用XMLHttpRequest对象的responseText属性访问“test.html”文件包含的内容。现在尝试一下responseXML属性。 首先,创建一个用于请求的名为“test.xml”的有效XML文档,代码如下: <?xml version="1.0" ?>
<root>
? ?I'm a test.
</root>
在脚本中,只需要修改请求行: onclick="makeRequest('test.xml')">
然后在alertContents()方法中,需要使用如下代码替换alert(httpRequest.responseText);这一行代码: var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);
这段代码需要由responseXML给予的XMLDocument对象,然后使用DOM方法来访问XML文档中的数据。 第五步:处理数据最后,向服务器端发送一些数据并接收响应。这次JavaScript脚本请求一个动态页面“test.php”,该页面将根据发送的数据返回一个“computedString”-“Hello,[user data]!”,并使用alert()方法进行打印。 首先,向HTML页面中添加一个文本框,用户可以通过该文本框输入他们的名字: <label>Your name:
?<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
?Make a request
</span>
还需要添加一行事件处理器用于从文本框获取用户的数据,并将该数据随着URL传递给makeRequest()方法: document.getElementById("ajaxButton").onclick = function() {
? ?var userName = document.getElementById("ajaxTextbox").value;
? ?makeRequest('test.php',userName);
};
修改makeRequest()方法用于接收用户数据并发送给服务器端。将请求方式从GET修改为POST,用户数据作为参数传递给httpRequest.send()方法: function makeRequest(url,userName) {
?...
?httpRequest.onreadystatechange = alertContents;
?httpRequest.open('POST',url);
?httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
?httpRequest.send('userName=' + encodeURIComponent(userName));
}
alertContents()方法可以向第三步一样利用alert()方法打印服务器端返回的数据。假设服务器端返回的是computedString和用户数据的话,如果用户在文本框中输入“Jane”服务器端响应的内容会像是这样: {“userData”:”Jane”,”computedString”:”Hi,Jane!”} 在alertContents()方法中使用这些数据,不仅可以使用alert()方法打印responseText的内容,还可以将其解析并打印computedString属性内容: function alertContents() {
?if (httpRequest.readyState === 4) {
? ?if (httpRequest.status === 200) {
? ? ?var response = JSON.parse(httpRequest.responseText);
? ? ?alert(response.computedString);
? ?} else {
? ? ?alert('There was a problem with the request.');
? ?}
?}
}
原文:https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started 译文:http://www.longestory.com/Ajax/ajax-getting-started.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |