
原型 - AJAX Response() 方法
此 AJAX Ajax.Response 是作為所有 Ajax 請求回撥的第一個引數傳遞的物件。
這是圍繞原生 xmlHttpRequest 物件的包裝器。它規範化了跨瀏覽器問題,同時透過 responseJSON 和 headerJSON 屬性添加了對 JSON 的支援。
Ajax.Response 物件的屬性
屬性 | 型別 | 描述 |
---|---|---|
狀態 | 數字 | 伺服器傳送的 HTTP 狀態程式碼。 |
statusText | 字串 | 伺服器傳送的 HTTP 狀態文字。 |
readyState | 數字 | 請求的當前狀態。0 對應於“未初始化”,1 對應於“載入中”,2 對應於“已載入”,3 對應於“互動式”和 4 對應於“完成”。 |
responseText | 字串 | 響應的文字主體。 |
responseXML | 文件物件 或空 |
如果請求的內容型別設定為 application/xml,則為響應的 XML 主體。否則為 null。 |
responseJSON | 物件,陣列 或空 |
如果請求的內容型別設定為 application/json,則為響應的 JSON 主體。否則為 null。 |
headerJSON | 物件,陣列 或空 |
如果存在,則為 X-JSON 標頭的自動評估內容。否則為 null。這對於傳輸少量資料很有用。 |
請求 | 物件 | 請求物件本身(Ajax.Request 或 Ajax.Updater 的例項)。 |
傳輸 | 物件 | 原生 xmlHttpRequest 物件本身。 |
例子
以下示例演示了 status 和 responseText 屬性的用法 -
<html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function SubmitRequest() { new Ajax.Request('/cgi-bin/ajax.cgi', { method: 'get', onSuccess: successFunc, onFailure: failureFunc }); } function successFunc(response) { if (200 == response.status) { alert("Call is success"); } var container = $('notice'); var content = response.responseText; container.update(content); } function failureFunc(response) { alert("Call is failed" ); } </script> </head> <body> <p>Click submit button to see how current notice changes.</p> <br /> <div id = "notice">Current Notice</div> <br /> <br /> <input type = "button" value = "Submit" onclick = "SubmitRequest();"/> </body> </html>
以下是 ajax.cgi 的內容。
#!/usr/bin/perl print "Content-type: text/html\n\n"; print "This content is returned by AJAX cgi
"; print "Current Time " . localtime;
輸出
Ajax.Response 物件的方法
方法 | 型別 | 描述 |
---|---|---|
getHeader(name) | 字串或 空 |
如果存在,則返回請求標頭的值。否則為 null。 |
getAllHeaders() | 字串或 空 |
返回一個包含所有標頭(以換行符分隔)的字串。 |
getResponseHeader(name) | 字串 | 如果存在,則返回請求標頭的值。否則丟擲錯誤。這只是圍繞 xmlHttpRequest 物件的原生方法的包裝器。更喜歡它更短的對應物 getHeader。 |
getAllResponseHeaders() | 字串 | 返回一個包含所有標頭(以換行符分隔)的字串。否則丟擲錯誤。這只是圍繞 xmlHttpRequest 物件的原生方法的包裝器。更喜歡它更短的對應物 getAllHeaders。 |
例子
以下示例演示了 getAllHeaders() 和 getResponseHeader(name) 方法的用法 -
<html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function SubmitRequest() { new Ajax.Request('/cgi-bin/ajax.cgi', { method: 'get', onSuccess: successFunc }); } function successFunc(response) { var content = response.getAllHeaders(); var container = $(header1); container.update(content); var content = response.getResponseHeader('Content-Type'); var container = $(header2); container.update(content); } </script> </head> <body> <p>Click submit button to see the result:</p> <br /> <div id = "header1">All Headers</div> <div id = "header2">Content Type</div> <br /> <br /> <input type = "button" value = "Submit" onclick = "SubmitRequest();"/> </body> </html>
輸出
prototype_ajax_tutorial.htm
廣告