原型 - AJAX 更新器() 方法



這個 AJAX Ajax.Updater 執行 AJAX 請求並根據響應文字更新容器的內容。

Ajax.Updater 是 Ajax.Request 的一個特例。

語法

new Ajax.Updater(container, url[, options]);

返回值

一個 AJAX Ajax.Updater 物件。

Ajax.Updater 包含所有 常用選項 和回撥函式,以及 Ajax.Updater(). 新增的那些。

此方法還有兩個特定選項:

選項 描述
evalScripts

預設值為 false.

這決定了是否評估響應文字中的 <script> 元素。

insertion

預設值為 None.

預設情況下,使用 Element.update,它用響應文字替換容器的全部內容。您可能希望改為在現有內容周圍插入響應文字。

在下面的示例中,我們假設透過 AJAX 建立新專案會返回僅表示新專案的 XHTML 片段,我們需要將其新增到我們的列表容器中,但在其現有內容的底部。如下所示:

new Ajax.Updater('items', '/items', {
   parameters: { text: $F('text') },
   insertion: Insertion.Bottom
});

示例

以下示例演示了使用 Ajax.Updater 更新系統時間的方法。每次時間都新增到底部:

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function insertTime() {
            new Ajax.Updater('datetime', '/cgi-bin/timer.cgi', {
               method: 'get', 
               insertion: Insertion.Bottom
            });
         }
      </script>
   </head>

   <body>
      <p>Click update button many time to see the result.</p>
      <br />
 
      <div id = "datetime">Date & Time</div>
      <br />
      <br />
      <input type = "button" value = "Update" onclick = "insertTime();"/>
   </body>
</html>

這是 timer.cgi 的內容。

#!/usr/bin/perl

print "Content-type: text/html\n\n";

$datetime = localtime;
print $datetime;
print "<br />";

輸出

單個容器,還是成功/失敗替代方案?

讓我們假設在上面的示例中,無論請求成功還是失敗,您都將更新相同的容器。很多時候您可能不希望這樣做。您可能只想對成功的請求進行更新,或者在請求失敗時更新不同的容器。

在下面的程式碼中,只有成功的請求才會更新:

new Ajax.Updater({ success: 'items' }, '/items', {
   parameters: { text: $F('text') },
   insertion: Insertion.Bottom
});

下一個示例假設失敗的請求將顯示錯誤訊息作為響應文字,並將繼續用它更新另一個元素,可能是一個狀態區域。

new Ajax.Updater({success:'items',failure:'notice' },'/items', {
   parameters: { text: $F('text') },
   insertion: Insertion.Bottom
});
prototype_ajax_tutorial.htm
廣告