Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

理解Ajax #14

Open
WarpPrism opened this issue Nov 13, 2016 · 0 comments
Open

理解Ajax #14

WarpPrism opened this issue Nov 13, 2016 · 0 comments

Comments

@WarpPrism
Copy link
Owner

WarpPrism commented Nov 13, 2016

Ajax = Asynchronous javascript and XML
Ajax 不是一种新的编程语言,而是使用现有技术的新标准。
Ajax 是在不重新加载整个页面的情况下,实现与服务器的数据交互并更新部分页面。

起源:

Google Suggest:当你在Google搜索框上输入关键字时,JavaScript会把这些字符发送到服务器,然后服务器会返回一个搜索建议的列表。

原理:

XMLHttpRequest对象是Ajax的基础,用于在Browser后台与服务器交换数据。

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

然后发送请求:

// true: async = true;
xmlhttp.open("GET/POST", url, true);
// send(string), string is only enabled when you use POST requset.
xmlhttp.send(null);

你有可能请求到缓存中的数据,为了避免这种情况,应在url后面加上 + Math.random()。

然后服务器响应:

xmlhttp.onreadystatechange = function() {
	if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
		// codes after response
	}
}

解释:
每当 readyState 改变时,就会触发 onreadystatechange 事件。readyState有5种状态,所以onreadystatechange函数在整个请求过程中会被调用5次。
如下所示:

• 0: 请求未初始化
• 1: 服务器连接已建立
• 2: 请求已接收
• 3: 请求处理中
• 4: 请求已完成,且响应已就绪

而status有以下两种状态:

200:OK
404: File Not Found

如果要获取服务器相应的内容,我们可以使用XMLHttpRequest对象的responseText和responseXML属性。

在实际开发过程中,我们一般使用回调函数callback的方法调用onreadystatechange:

var xmlhttp;
function ajaxReq(url, callback) {
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {
		// code for IE5, 6
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = callback;
	xmlhttp.open("GET", url, true);
	xmlhttp.send(null);
}

ajaxReq(myurl, function() {
	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
		document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
	}
});

jQuery中的Ajax:

编写常规的 AJAX 代码并不容易,因为不同的浏览器对 AJAX 的实现并不相同。这意味着您必须编写额外的代码对浏览器进行测试。不过,jQuery 团队为我们解决了这个难题,我们只需要一行简单的代码,就可以实现 AJAX 功能。

ajax方法(常用):

$.ajax({
	type: "POST/GET"
	async: true,
	url: "server/handle.php",
	data: {username:$("#username").val(), content:$("#content").val()},
	dataType: "json",
	success: function(data) {
		// codes when response is ready
	}
});

load方法:

load() 方法从服务器加载数据,并把返回的数据放入被选元素中。

$(selector).load(URL,data,callback);

必需的 URL 参数规定您希望加载的 URL。
可选的 data 参数规定与请求一同发送的查询字符串键/值对集合。
可选的 callback 参数是 load() 方法完成后所执行的函数名称。

get方法:

// $.get(URL,callback);
$("button").click(function(){
	$.get("demo_test.asp",function(data,status) {
		alert("Data: " + data + "\nStatus: " + status);
	});
});

asp文件:

<%
response.write("This is some text from an external ASP file.")
%>

post方法:

// $.post(URL,data,callback);
$("button").click(function(){
	$.post("demo_test_post.asp",
		{
			name:"Donald Duck",
			city:"Duckburg"
		},
		function(data,status){
			alert("Data: " + data + "\nStatus: " + status);
		});
});

asp文件:

<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant