dev2dev 首页 > 资源中心 > 专家Blog > 专家Blog文章
AJAX——那不是多伦多的一个小镇吗?
AJAX(Asynchronous JavaScript And XML)是用于创建动态web应用程序的web开发技术。然而,它不仅仅是这些。AJAX背后的主要驱动力量是与后台服务器交换少量数据,从而通过避免在每次用户进行更改/请求时重新加载整个web页面的方式提高性能。我经常使用的一些示例AJAX应用程序是GMail、Google Maps和Google Suggest。
术语AJAX是指以下各项的组合:
- 面向标记和样式的HTML/XHTML、CSS
- JavaScript,用于对服务器请求/响应
- DHTML(Dynamic HTML)帮助更新表单
- XML,通常用作将数据从服务器传送回来的格式
- 使用客户端脚本语言(如JavaScript)访问的DOM(Document Object Model)
要使用JavaScript向服务器发送HTTP请求,可以使用XMLHttpRequest类。以下是来自mozilla开发人员中心的示例: http://developer.mozilla.org/en/docs/AJAX:Getting_Started
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
// See note below about this line
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() { alertContents(http_request); };
http_request.open('GET', url, true);
http_request.send(null);
}
function alertContents(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
XMLHttpRequest对象处理所有的服务器通信。所以JavaScript代码在后台发送请求。请求也被异步发送,所以用户不必等待服务器响应。
如果使用XMLHttpRequest,就可以使用余下的JavaScript代码从HTML获得表单数据,并将它发送到服务器。也可以使用JavaScript动态更新表单或更改字段值。JavaScript也可用于解析DOM以及与从服务器返回的HTML表单和XML数据协作。
// Get the value of the "name" field and put it in variable name
var name = document.getElementById("name").value;
Notice in the above code, the XMLHttpRequest object depends on the browser type.
function requestServer() {
// Get the name from form
var name = document.getElementById("name").value;
// check if name is null or blank
if ((name == null) || (name == "")) return;
// Build the URL to connect to
var url = "/MyApp/getID?name=" + escape(name);
// Open a connection to the server
xmlHttp.open("GET", url, true);
// Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = refreshPage;
// Send the request
xmlHttp.send(null);
}
function refreshPage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("id").value = response;
}
}
使用以上代码可以从表单获取名称,并呼叫服务器获取ID。RefreshPage函数显示不会进行任何操作,直到xmlHttp.readyState等于4,服务器会将响应放入xmlHttp.responseText属性。
现在,唯一余下的就是启动一切的HTML表格了:
<form>
Name: <input type="text" name="state" id="state" size="25"
onChange="requestServer();" />
<br>
ID: <input type="text" name="id" id="id" size="10"/>
</form>
这可能是最简单的显示页面动态更新而不刷新整个页面的示例。有关AJAX的更多信息,请阅读此dev2dev文章:Ajax简介http://dev2dev.bea.com.cn/techdoc/2005110103.html
原文出处:http://dev2dev.bea.com/blog/shengs75/archive/2006/03/ajax_isnt_that_1.html
作者其它文章
|