类似Twitter的内容提交和更新

发布于 2024-10-14 17:13:56 字数 2850 浏览 2 评论 0原文

问候。我现在正在创建一个报价服务,并在尝试进行类似twitter的数据提交和显示时鼓励出现这样的问题:我所有的ajax请求都执行了两次。我使用 jQuery 的方式如下:

  • 我尝试过 .click().live("click", function())。带有“提交”按钮的 one("click", function()) 处理程序。他们都执行了两次查询。是的,还有 .one("click", function())

  • 我设置了超时函数来检查新报价,它也执行了两次

我的 JS/RoR 代码有什么问题吗?

您可以在 github 上查看我的所有资源。

任何帮助都会很棒。

UPD:这是我的表单生成的 HTML:

<div class="msg"></div><br />
<form accept-charset="UTF-8" action="/quotes" class="new_quote" id="new_quote" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="vD6hAOmZjenRFw1aO1yH75K9K7WTFneJuP3H7sOR/Qw=" /></div>

  <div class="field">
    <label for="quote_author">Author</label><br />
    <input id="quote_author" name="quote[author]" size="30" type="text" />
  </div>
  <div class="field">
    <label for="quote_body">Body</label><br />
    <textarea cols="60" id="quote_body" name="quote[body]" rows="8"></textarea>

  </div>
    <div class="field">
      <label for="quote_approved">Approved</label><br />
      <input name="quote[approved]" type="hidden" value="0" /><input id="quote_approved" name="quote[approved]" type="checkbox" value="1" />
    </div>
  <div class="actions">
    <input id="quote_submit" name="commit" type="submit" value="Create Quote" />
  </div>

</form>

这是我的 javascript:

onerror = function moo(msg, url, line) {
//alert('Error: ' + msg + '\nURL: ' + url + '\nLine: ' + line);
}

function moo() {
var cnt = 0, type = "";
var id = $("div.quote:first").attr("id");

$.getJSON("/after/" + id, function(data) {
var cnt = data.length;

if (cnt > 0)
$(".msg").css("backgrount-color", "#ffff00").text(cnt + " new quotes added. Please, update").fadeIn('slow').delay(20000).fadeOut('slow');
});

setTimeout("moo()", 30000);
}

$(document).ready(function() {
var to = setTimeout("moo()", 30000);

$.getJSON("/author_list", function(data) {
$("#quote_author").autocomplete({ source: data, minLength: 1 })
});

$("form.new_quote > .actions > [type=submit]").live("click", function() {
$.post('/ajax_new', $('form.new_quote').serialize(), function(resp) {
resp = $.parseJSON(resp);

if (resp[0].done == "ok") {
$(".msg").css("background-color", "#00fe00").text("Ok").fadeIn('slow').delay(5000).fadeOut('slow');
$("#quote_author,#quote_body").each(function(i,e) {
$(this).val("");
});
}
});

return false;
});
});

Greetings. I'm creating a quotation service now and encouraged such a problem while trying to make twitter-like data submission and display: all my ajax requests are executed twice. I'm using jQuery as follows:

  • i've tried .click(), .live("click", function()) and .one("click", function()) handlers with "submit" button. All of them executed query twice. And yes, the .one("click", function()) too.

  • i set timeout function to check for new quotes and it is executed twice too

What's wrong with my JS/RoR code?

You can see all my sources at github.

Any help would be great.

UPD: Here's my form resulting HTML:

<div class="msg"></div><br />
<form accept-charset="UTF-8" action="/quotes" class="new_quote" id="new_quote" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="vD6hAOmZjenRFw1aO1yH75K9K7WTFneJuP3H7sOR/Qw=" /></div>

  <div class="field">
    <label for="quote_author">Author</label><br />
    <input id="quote_author" name="quote[author]" size="30" type="text" />
  </div>
  <div class="field">
    <label for="quote_body">Body</label><br />
    <textarea cols="60" id="quote_body" name="quote[body]" rows="8"></textarea>

  </div>
    <div class="field">
      <label for="quote_approved">Approved</label><br />
      <input name="quote[approved]" type="hidden" value="0" /><input id="quote_approved" name="quote[approved]" type="checkbox" value="1" />
    </div>
  <div class="actions">
    <input id="quote_submit" name="commit" type="submit" value="Create Quote" />
  </div>

</form>

And here's my javascript:

onerror = function moo(msg, url, line) {
//alert('Error: ' + msg + '\nURL: ' + url + '\nLine: ' + line);
}

function moo() {
var cnt = 0, type = "";
var id = $("div.quote:first").attr("id");

$.getJSON("/after/" + id, function(data) {
var cnt = data.length;

if (cnt > 0)
$(".msg").css("backgrount-color", "#ffff00").text(cnt + " new quotes added. Please, update").fadeIn('slow').delay(20000).fadeOut('slow');
});

setTimeout("moo()", 30000);
}

$(document).ready(function() {
var to = setTimeout("moo()", 30000);

$.getJSON("/author_list", function(data) {
$("#quote_author").autocomplete({ source: data, minLength: 1 })
});

$("form.new_quote > .actions > [type=submit]").live("click", function() {
$.post('/ajax_new', $('form.new_quote').serialize(), function(resp) {
resp = $.parseJSON(resp);

if (resp[0].done == "ok") {
$(".msg").css("background-color", "#00fe00").text("Ok").fadeIn('slow').delay(5000).fadeOut('slow');
$("#quote_author,#quote_body").each(function(i,e) {
$(this).val("");
});
}
});

return false;
});
});

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

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

发布评论

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

评论(1

相对绾红妆 2024-10-21 17:13:56

我已经浏览了你的消息来源。恕我直言,实现目标的更好方法是以 Rails 方式实现。我的意思是你已经使用了 jquery Rails 脚本。因此,您可以在 Rails 3 应用程序中轻松地坚持使用 UJS 和 RJS 方法:

在表单中:

form_for(@quote, :remote => true) do |f|

在控制器中:

  def create
    @quote = Quote.new(params[:quote])

    respond_to do |format|
      if @quote.save
        format.html { redirect_to(@quote, :notice => :quote_created) }
        format.xml  { render :xml => @quote, :status => :created, :location => @quote }
        format.js 
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @quote.errors, :status => :unprocessable_entity }
        format.js 
      end
    end
  end

在 create.js.erb 中(下面是 HAML 语法):

- if @quote.errors.any?
  $('#data_form').html('#{escape_javascript(render(:partial => "form"))}');
- else
  $('ul.data_grid').prepend('#{escape_javascript(render :partial => "quote", :locals => { :quote => quote })}');

您可以使用 #data_form 包装表单,并使用 ul.data_grid 包装引号列表,或者更改 create.js.erb 中的选择器。此外,在该文件中,您可以清除成功时的表单并显示即时消息或此处所需的任何内容。

毕竟,不要忘记从 application.js 中删除此代码(不再需要了):

$("form.new_quote > .actions > [type=submit]").live("click", function() {
    $.post('/ajax_new', $('form.new_quote').serialize(), function(resp) {
            resp = $.parseJSON(resp);

            if (resp[0].done == "ok") {
                $(".msg").css("background-color", "#00fe00").text("Ok").fadeIn('slow').delay(5000).fadeOut('slow');
                $("#quote_author,#quote_body").each(function(i,e) {
                    $(this).val("");
                });
            }
        });

    return false;
});

I have looked through your sources. IMHO the better way to achieve your goal is to do it in the Rails way. I mean that you already use jquery rails script. So you can easily stick to UJS with RJS approach in your rails 3 application:

In form:

form_for(@quote, :remote => true) do |f|

In controller:

  def create
    @quote = Quote.new(params[:quote])

    respond_to do |format|
      if @quote.save
        format.html { redirect_to(@quote, :notice => :quote_created) }
        format.xml  { render :xml => @quote, :status => :created, :location => @quote }
        format.js 
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @quote.errors, :status => :unprocessable_entity }
        format.js 
      end
    end
  end

In create.js.erb (below is HAML syntax):

- if @quote.errors.any?
  $('#data_form').html('#{escape_javascript(render(:partial => "form"))}');
- else
  $('ul.data_grid').prepend('#{escape_javascript(render :partial => "quote", :locals => { :quote => quote })}');

You can wrap your form with #data_form and quotes list with ul.data_grid or change selectors in create.js.erb. Also in that file you can clear form on success and show flash messages or whatever you need here.

After all don't forget to throw out this code from application.js (it's unnecessary any more):

$("form.new_quote > .actions > [type=submit]").live("click", function() {
    $.post('/ajax_new', $('form.new_quote').serialize(), function(resp) {
            resp = $.parseJSON(resp);

            if (resp[0].done == "ok") {
                $(".msg").css("background-color", "#00fe00").text("Ok").fadeIn('slow').delay(5000).fadeOut('slow');
                $("#quote_author,#quote_body").each(function(i,e) {
                    $(this).val("");
                });
            }
        });

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