[关闭]
@czyczk 2018-01-28T13:58:34.000000Z 字数 7697 阅读 192

Ajax

Front-End Ajax jQuery



1 基础姿势

1.1 XMLHttpRequest

XMLHttpRequest 是 Ajax 的基础,用于与后台交换数据,在不刷新页面的情况下更新内容。
除 IE5、IE6 等老浏览器不内建 XMLHttpRequest,要用 ActiveX 对象。

  1. var xmlhttp;
  2. if (window.XMLHttpRequest) {
  3. // IE7+、Firefox、Chrome、Opera 等执行
  4. xmlhttp = new XMLHttpRequest();
  5. } else {
  6. // IE6、IE5 浏览器执行
  7. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  8. }

1.2 向服务器发送请求

  1. xmlhttp.open("GET", "ajax_info.txt", true);
  2. xmlhttp.send();
方法 描述
open(method, url, async) method: GET 或 POST;url: 服务器上的文件位置;async: true 或 false。请求的文件可以是文本或脚本等。用于 AJAX 时必须使用异步。
send(string) string: 仅用于 POST。
setRequestHeader(header, value) 向请求添加 HTTP 头。

发送 POST 请求。

  1. xmlhttp.open("POST", "/try/ajax/demo_post.php", true);
  2. xmlhttp.send();

若要发送表单,使用 setRequestHeader() 来添加 HTTP 头。

  1. xmlhttp.open("POST", "/try/ajax/demo_post2.php", true);
  2. xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 参数为 header, content
  3. xmlhttp.send("fname=Henry&lname=Ford");

请求一个文本文档,并根据它覆写页面内容。

  1. xmlhttp.open("GET", "/try/ajax/ajax_info.txt", true);
  2. xmlhttp.send();
  3. document.getElementById("myDiv").innerHTML = xmlhttp.resposeText;

关于服务器来的回应详见下节。

1.3 处理来自服务器的响应

包含在 xmlhttp 对象中。

属性 描述
responseText 获得响应数据(字符串形式)。
responseXML 获得响应数据(XML 形式)。
  1. document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  1. xmlDoc = xmlhttp.responseXML;
  2. txt = "";
  3. x = xmlDoc.getElementsByTagName("ARTIST");
  4. for (i = 0; i < x.length; i++) {
  5. txt = txt + x[i].childNodes[0].nodeValue + "<br>";
  6. }
  7. document.getElementById("myDiv").innerHTML=txt;

1.4 onreadystatechange 事件

XMLHttpRequest 中有 readyState 属性,它存着 XMLHttpRequest 的状态信息。
下面是 XMLHttpRequest 的三个重要信息:

属性 描述
onreadystatechange 本身是个函数。每当 readyState 发生改变时,就触发这个函数。
readyState 存有 XMLHttpRequest 的状态。0:请求未初始化;1:服务器连接已建立;2:请求已接收;3:请求处理中;4:请求已完成,且响应已就绪。
status 200:OK;404:页面未找到。

每当 readyState 被改变时就会触发这个事件(在一个完整的请求中,这个事件被触发 5 次)。
通常我们要在状态为成功的时候,即 readyState == 4 && status == 200 时处理事件。

  1. xmlhttp.onreadychange = function() {
  2. if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  3. document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
  4. }
  5. }

上面这种写法中,所有请求都会触发相同的事件,产生相同的行为。如果要为不同的请求定义不同的行为,可以使用回调函数(把一个函数(可以是匿名函数)作为参数)。

  1. function performWhenClicked() {
  2. loadXMLDoc("/try/ajax/ajax_info.txt", function() {
  3. if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  4. document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
  5. }
  6. });
  7. }

2 Starting Again with jQuery

2.1 Requests

A very basic request (minimal form):

  1. $.ajax({ url: "address", success: handlerFunction} );

Simple handler (the contents in the address are passed into the handler function as parameters).
For example:

  1. function logText(text) {
  2. console.log("Text from server is %o.", text);
  3. }
  4. $.ajax({ url: "server-result.txt", success: logText });
  1. $.ajax({ ... });
Option Description
url Almost always used.
success Almost always used. Invoke the success handler function (can be an array of functions).
cache When using "GET" method, browsers are allowed to cache the result. If cache is enabled, you may get the earlier result again.
data Data to be sent to the URL (/ server).
dataType ..
error The function to handle errors.
type ..
username ..
password ..
  1. $.ajax({ url: "target.txt", success: successHandler, error: errorHandler });
  2. $.ajax({ url: "target.txt", success: [handler1, handler2, ...] });
Cache
    In "GET" method, browsers are permitted to cache the result (if enabled in the browser as well). So you may get the same result again if the request URLs are the same. It's good to cache for the same request sometimes, but if you want to ensure you get the latest or different result for the same request, set cache to false or use "POST" method.

2.2 Handler Functions

  1. function someHandler(text, status, request) { ... }
Option Description
text Contents in the requested file. Response data from server.
status "success" or "notmodified". Meaningful in error handlers.
request The XMLHttpRequest object mentioned in the previous sections.

3 Dealing with Dynamic Contents

3.1 Requests for Scripts

3.1.1 An Example

server-time.jsp

  1. It is now <=% new java.util.Date() %>

someScript.js

  1. function showTime(text) {
  2. $.ajax({ url: "server-time.jsp", cache: "false", success: logText });
  3. }
  4. function logText(text) { ... }

somePage.html

  1. <html>
  2. <head>
  3. ...
  4. <script src="scripts/jquery.js"></script>
  5. <script src="scripts/someScript.js"></script>
  6. </head>
  7. <body>
  8. ...
  9. <input type="button" id="showTimeButton" value="Show Time" onclick="showTime()" />
  10. </body>

3.1.2 Unobstructive Javascript

In the example in the previous section, elements in an HTML document need to register handlers. In the fashion of jQuery, it's more encouraged to register handlers in Javascript scripts instead of in the elements.
someScript.js

  1. $(function() {
  2. // This function runs after the DOM is loaded, but does not wait for images,
  3. // as with window.onload in raw Javascript.
  4. // Use this approach to set up all event handlers
  5. // $("#elementId").click(someHandler);
  6. $("#showTimeButton").click(showTime);
  7. });
  8. function showTime...

3.2 Manipulating HTML Elements

3.2.1 General Procedures

  1. $("some").html(result); // The result can be text response from the server or the proccessed text.

Usually, first prepare some elements identified with IDs in the HTML pages.
For example:

  1. <div id="resultDiv"></div>
  2. <span id="targetSpan"></span>

3.2.2 Do Quick Insertion

Use the built-in handler.

  1. $(function{
  2. $("#show-time-button-2").click(showTime2);
  3. });
  4. function showTime2() {
  5. insertAjaxResult("show-time.jsp", "#time-result");
  6. }
  1. // Simplest form
  2. $("#result-area-id").load("url");
  3. // Most common form in real life. Pass data to the url, retrieve the contents and insert them to the element
  4. $("#result-area-id").load("url", data);
  5. // + an additional handler that is invoked after the built-in handler
  6. $("#result-area-id").load("url", data, handlerFunction);
  1. $("#waiting-message-div").show();
  2. $("#result-div").load("some-url");
  3. $("#waiting-message-div").hide();

3.3 Sending Data to the Server

  1. $.ajax({ ... data: "name1=foo+bar%21&name2=baz" });
  1. $.ajax({ ... data: { name1: "foo bar!", name2: "baz" } });
  1. $.ajax({ ... data: $("#form-id").serialize() });

3.3.1 Shortcuts

  1. $.get("url", dataObj, someFunc);
  2. $.ajax({ url: "url", data: dataObj, success: someFunc });
  1. $.post("url", dataObj, someFunc);
  2. $.ajax({ url: "url", data: dataObj, success: someFunc, type: "post" });
  1. $.getJSON("url", dataObj, someFunc);
  2. $.ajax({ url: "url", data: dataObj, success: someFunc, dataType: "json" });

3.4 Receiving JSON Objects

  1. function showCto() {
  2. $.ajax({ url: "executives.json", dataType: "json", success: showCtoHeading });
  3. }
  4. function showCtoHeading(companyExecutives) {
  5. // The receivied JSON string is automatically parsed into an object
  6. $("#cto-result").html("<h2>Chief Technology Officer is: " + companyExecutives.cto + "</h2>");
  7. }

4 Promises and Deferred Objects

4.1 Making Handlers More Modular and Reusable

Replace

  1. $.ajax({ url: remoteAddress,
  2. success: successHandler,
  3. complete: completeHandler,
  4. error: errorHandler });

with this:

  1. var req = $.ajax({ url: remoteAddress });
  2. req.done(successHandler);
  3. req.always(completeHandler);
  4. req.fail(errorHandler);

If additional handlers need to be added, simply do:

  1. req.done(additionalSuccessHandler);

常见服务器状态码

服务器常用的状态码及其对应的含义如下:

200:服务器响应正常。
304:该资源在上次请求之后没有任何修改(这通常用于浏览器的缓存机制,使用GET请求时尤其需要注意)。
400:无法找到请求的资源。
401:访问资源的权限不够。
403:没有权限访问资源。
404:需要访问的资源不存在。
405:需要访问的资源被禁止。
407:访问的资源需要代理身份验证。
414:请求的URL太长。
500:服务器内部错误。
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注