Prototype - AJAX Updater() 方法

此 AJAX Ajax.Updater 执行 AJAX 请求并根据响应文本更新容器的内容。

Ajax.Updater 是 Ajax.Request 的特化。

语法

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

返回值

AJAX Ajax.Updater 对象。

Ajax.Updater 包含所有常用选项和回调,以及由 Ajax.Updater(). 添加的选项。

此方法还有两个特定选项 −

选项 说明
evalScripts

默认值为 false。

这决定了是否评估响应文本中的 <script> 元素。

插入

默认值为 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

";

$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.html