AJAX Updater() 方法 | Prototype教程

返回到:Prototype 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默认值为无
默认情况下,使用 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 = "https://cdn.bootcdn.net/ajax/libs/prototype/1.7.3/prototype.min.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 教程

作者:terry,如若转载,请注明出处:https://www.web176.com/prototype_api/8283.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年1月24日
下一篇 2023年1月25日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注