Categories: Prototype Api

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

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

聊聊vue3中的defineProps

在Vue 3中,defineP…

2 天 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

7 天 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

2 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

3 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

3 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

4 周 ago