Rails ajax 后台请求

发布于 2024-08-17 18:20:01 字数 1460 浏览 4 评论 0原文

我有一个 100% 工作的远程表单,

当用户单击提交时,它会从数据库中获取数据或从另一个网站上抓取数据,并无缝更新页面...

我现在遇到的问题是,我'我想做同样的事情,但不需要用户单击带有 onload 事件的提交按钮。我认为我的处理方式是错误的:

从技术上讲,这是可行的......它确实获得了正确的数据,但它并没有完全执行remote_form_tag 所做的事情,而是返回原始数据。没有 RJS Replace_html。

有没有办法完全跳过 form_for 并在页面加载时直接执行控制器操作?

<script type="text/javascript">
    $(window).load(function() {
        // executes when HTML-Document is loaded and DOM is ready
        // jQuery.facebox('Big loading! <img alt=\"Loading\" src=\"/images/loaders/loading.gif\" />');
        //$("#update_form").submit();
        $("#update_form").submit(function () { return false; });

    });
</script>

的表格

#html.erb
<%  form_remote_tag :url => { :action => "update_availables", :id => params[:id] },
    :loading => "jQuery.facebox('Big loading! <img alt=\"Loading\" src=\"/images/loaders/loading.gif\" />');",
    :html => { :method => "get" },
    :method => "get",
    :html => { :id => 'update_form' } do %>

控制器

  def update_availables
    @do_it = Available.get_new_availables :id => params[:id], :date => user_cart.getDate.to_s
    get_availables

    respond_to do |format|
      format.html
      format.js
    end
  end

RJS

page.replace_html :rooms, :partial => "available"
page << "jQuery.facebox.close();"

I have a remote_form which works 100%

When a user clicks submit, it goes out grabs so data from the db or data scraped from another website, and updates the page seamlessly...

The problem I'm having now, is that I'd like to do the same thing, but do it without having the user click the submit button with an onload event. I think I'm going about it the wrong way:

Technically this works... it does get the right data, but instead of doing exactly what the remote_form_tag does it returns the data raw. No RJS replace_html.

Is there a way to skip the form_for altogether and just execute the controller action directly when the page loads?

<script type="text/javascript">
    $(window).load(function() {
        // executes when HTML-Document is loaded and DOM is ready
        // jQuery.facebox('Big loading! <img alt=\"Loading\" src=\"/images/loaders/loading.gif\" />');
        //$("#update_form").submit();
        $("#update_form").submit(function () { return false; });

    });
</script>

The form for

#html.erb
<%  form_remote_tag :url => { :action => "update_availables", :id => params[:id] },
    :loading => "jQuery.facebox('Big loading! <img alt=\"Loading\" src=\"/images/loaders/loading.gif\" />');",
    :html => { :method => "get" },
    :method => "get",
    :html => { :id => 'update_form' } do %>

The controller

  def update_availables
    @do_it = Available.get_new_availables :id => params[:id], :date => user_cart.getDate.to_s
    get_availables

    respond_to do |format|
      format.html
      format.js
    end
  end

RJS

page.replace_html :rooms, :partial => "available"
page << "jQuery.facebox.close();"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最美不过初阳 2024-08-24 18:20:01

那么,要获得与用户单击表单相同的功能,您可以使用 javascript click 方法:

$(window).load(function() {

    $("#update_form input[type='submit']").click();

});

但是,如果您在没有用户任何输入的情况下提交,为什么要将数据放入表单中为什么不直接在加载处理程序中放置一个 ajax 调用来调用操作并直接更新代码呢?

$(window).load(function() {

    $.ajax({
      type: "GET",
      url: "scraper_url",
      data: {field1:val,field2:val},
      success: function(responseText){
        // update page
      }
    });

});

Well, to get the same functionality as the user clicking the form you could use the javascript click method:

$(window).load(function() {

    $("#update_form input[type='submit']").click();

});

But, if you're submitting without any input from the user, why put the data in a form at all, why not just put an ajax call in the load handler which calls the action and updates the code directly?

$(window).load(function() {

    $.ajax({
      type: "GET",
      url: "scraper_url",
      data: {field1:val,field2:val},
      success: function(responseText){
        // update page
      }
    });

});
浅浅淡淡 2024-08-24 18:20:01

我同意弗洛伊德的观点。我通常处理此类事情的方法是从 Rails 操作返回必要的 JSON 数据,而不是使用 RJS 更新页面。这样做的好处是,JSON 的生成速度通常非常快,并且可以轻松地将其作为 to_json 方法移动到模型中,并在许多不同的上下文中重用。

如果更新页面很简单,那么您没有理由不能像这样内联执行此操作,但如果更复杂,您可以将其定义为静态 javascript 文件中的函数。这种方法的好处是它使您的 javascript 和 ruby​​ 代码更加模块化和解耦。调试和单元测试更容易,因为 javascript 代码独立存在,而不是被有限的 RJS 方法泄漏地“抽象”(更像是混淆)。您还可以从静态 JavaScript 文件缓存中获得一些性能优势。

如果您浏览一下网络,您会发现 Rails 博客中最近没有太多提及 RJS。这是因为 RJS 在 2006 年是一个热门想法,但随着 javascript 最佳实践的发展而被废弃。要理解这一点,您需要查看 AJAX 的历史。 Rails 是 2005 年第一个内置 AJAX 支持的框架之一,它使用 Prototype 实现这一点,Prototype 实际上是第一个现代 Javascript 框架,但仍然很粗糙。当时,大量 Web 开发人员正在寻找任何方法来避免使用 Javascript,由于 DOM 不兼容,Javascript 名声不佳。因此,人们有点过于急于用 Rails 助手来掩盖一切。当人们对非常简单的 AJAX 感到惊叹时,这真是太棒了,但随着 Javascript 框架的成熟,人们对 Javascript 功能变得更加雄心勃勃,很明显 Javascript 应该成为一等公民。如今,jQuery 使常见的 javascript 任务变得如此简洁和优雅,以至于早期的 Rails 助手即使在默认功能有效的情况下也显得笨拙。 RJS 可能仍然有一些很好的用例,但我已经很多年没有使用它了,而且我根本没有错过它。

我的建议是拥抱 Javascript。学习 Douglas Crockford 的 Javascript: The Good Parts,然后花大量时间学习 jQuery。你将会得到丰厚的回报。

I agree with floyd here. The way I usually approach this type of thing is to return the necessary JSON data from the Rails actions rather than using RJS to update the page. This has the benefits that JSON is usually very fast to generate, and it can easily be moved to the model as a to_json method and reused in many different contexts.

If updating the page is simple there's no reason you can't do it inline like this, but if it's more complex you can define it as a function in a static javascript file. The nice thing about that approach is that it keeps your javascript and ruby code more modular and decoupled. It's easier to debug and unit test because the javascript code stands on its own rather than being leakily "abstracted" (more like obfuscated) by the limited RJS methods. You also gain some performance benefits from static javascript file caching as well.

If you look around the web you'll notice there's not much mention of RJS recently in Rails blogs. That's because RJS was a hot idea back in 2006, but has fallen into disuse as javascript best practices have evolved. To understand this, you need to look at the history of AJAX. Rails was one of the first frameworks to have built-in AJAX support in 2005, and it did so using Prototype which was really the first modern Javascript framework but was still quite rough around the edges. At the time a very large number of web developers were looking for any way to avoid Javascript, which had an undeservedly terrible reputation due to DOM incompatibilities. Therefore people were a little overeager to paper over everything with Rails helpers. This was great when people were wowed with very simple AJAX, but as Javascript frameworks matured and people became more ambitious with their Javascript functionality it became clear that Javascript deserves to be a first-class citizen. Nowadays jQuery makes common javascript tasks so concise and elegant that the early Rails helpers appear clumsy even when their default functionality works. There are still probably some good use cases for RJS, but I haven't used it for years and I haven't missed it at all.

My advice is to embrace Javascript. Pick up Javascript: The Good Parts by Douglas Crockford, and then spend a lot of time with jQuery. You will be well-rewarded.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文