Ajax 的定义
Ajax 是 Asynchronous JavaScript and XML(以及 DHTML 等)的缩写。这个短语是 Adaptive Path 的 Jesse James Garrett 发明的,按照 Jesse 的解释,这不是 个首字母缩写词。
下面是 Ajax 应用程序所用到的基本技术:
* HTML---------用于建立 Web 表单并确定应用程序其他部分使用的字段。
* JavaScript 代码-----是运行 Ajax 应用程序的核心代码,帮助改进与服务器应用程序的通信。
* DHTML 或 Dynamic HTML,用于动态更新表单。我们将使用 div 、span 和其他动态 HTML 元素来标记 HTML。
* 文档对象模型 DOM 用于(通过 JavaScript 代码)处理 HTML 结构和(某些情况下)服务器返回的 XML。
XMLHttpRequest 对象是处理所有服务器通信的对象。
window.onload = function() {}); 原生js
$()
函数的三种用法
$(window).load(function() {});
$(document).ready(function() {});
$(function() {});
$('#message').css('background', 'yellow').html('Hello!').show(); 方法链接
$.post() 或者 $.get()
$.post('save.cgi', {
text: 'my string',
number: 23
}, function() {
alert('Your data has been saved.');
});
$.ajax() 函数
可以指定 xml、script、html 或者 json,jQuery 将自动为回调函数准备合适的结果,这样您便可以立即使用该结果。还可以指定 beforeSend、error、success 或者 complete
回调函数,向用户提供更多有关 Ajax 体验的反馈。
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
@cc_on 语句可以在脚本的注释内启用 条件编译功能。
XMLHttpRequest请求
1. 从 Web 表单中获取需要的数据。
2. 建立要连接的 URL。
3. 打开到服务器的连接。
4. 设置服务器在完成后要运行的函数。
5. 发送请求。
function callServer() {
// Get the city and state from the web form
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
// Only go on if there are values for both fields
if ((city == null) || (city == "")) return;
if ((state == null) || (state == "")) return;
// Build the URL to connect to
var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);
// 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 = updatePage;
// Send the request
xmlHttp.send(null);
}
xmlHttp (要记住,这是 XMLHttpRequest 对象实例)的 onreadystatechange 属性可以告诉服务器在运行完成后(可能要用五分钟或者五个小时)做什么处理响应现在要面对服务器的响应了。现在只要知道两点:
* 什么也不要做,直到 xmlHttp.readyState 属性的值等于4。
* 服务器将把响应填充到 xmlHttp.responseText 属性中。
function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("zipCode").value = response;
}
}