简体   繁体   English

使用jQuery和Ajax提交Rails表单

[英]Submitting a Rails form with jQuery and Ajax

EDIT: Figured it out so asking a related question. 编辑:弄清楚了,所以问一个相关的问题。

here's my Javascript 这是我的Javascript

jQuery.ajaxSetup({
    'beforeSend': function(xhr) {
        xhr.setRequestHeader("Accept", "text/javascript")
    }
})

jQuery.fn.submitWithAjax = function() {
    this.submit(function() {
        $.post(this.action, $(this).serialize(), null, "script");
        return false;
    })
    return this;
};

    $('.error').hide();
$("#business_submit").click(function() {
    // validate and process form here

    $('.error').hide();
    var name = $("input#business_name").val();
    if (name == ""  || name == "Required Field") {
        $('#namelabel').show()
        $("#business_name").focus();
        return false;
    }
    var address = $("#business_address").val();
    if (address == ""  || address == "Required Field") {
        $('#addresslabel').show();
        $("#business_address").focus();
        return false;
    }
    var city = $("#business_city").val();
    if (city == "" || city == "Required Field") {
        $('#citylabel').show();
        $('#business_city').focus();
        return false;
    }
    var state = $("#business_state").val();
    if (state == ""  || state == "Required Field") {
        $('#statelabel').show();
        $("#business_state").focus();
        return false;
    }
    var zip = $("#business_zip").val();
    if (zip == ""  || zip == "Required Field") {
        $('#ziplabel').show();
        $("#business_zip").focus();
        return false;
    }
    var phone = $("#business_phone").val();
    if (phone == ""  || phone == "Required Field") {
        $('#phonelabel').show();
        $("#business_phone").focus();
        return false;
    }

    var category = $("#business_business_category_id").val();
    if (category == " - Choose one - ") {
        $('#categorylabel').show();
        $("#business_business_category_id").focus();
        return false;
    }


   $.ajax ({
        type: "POST",
        data: form.serialize()
    });
    return false;
})

the .ajax code fires my create.js.erb file which contains .ajax代码会触发我的create.js.erb文件,其中包含

$("#new_business").submitWithAjax();
$("#new_business")[0].reset();
$("#new_business").hide();

Here's the table below the form. 这是表格下方的表格。

<div id="unapproved">
  <table width="650" align="center" cellpadding="6" cellspacing="0">

    <tr>
      <td width="150"><a class="Contact<%=h @business.id %>" href="#"><%=h @business.name %></a></td>
      <td width="150"><%=h @business.address %></td>
      <td width="100"><%=h @business.business_category.name %></td>
      <td width="200"><%=h @business.description %></td>
      <td width="50"><%= link_to(image_tag('/images/accept.png', :alt => 'Approve'), :id =>@business.id, :action => 'approve') %>
        <a class="Edit<%=h @business.id %>" href="#"><img src="/images/pencil.png" alt="Edit" /></a>
      <%= link_to(image_tag('/images/bin.png', :alt => 'Remove'), @business, :confirm => 'Are you sure?', :method => :delete) %></td>
    </tr>
  </table>
</div>

Now my only problem is that the table below my form isn't getting refreshed dynamically. 现在,我唯一的问题是表格下方的表格无法动态刷新。 It adds the data to the database fine and all the validation works great. 它将数据很好地添加到数据库中,并且所有验证工作都很好。 But I have to refresh the page. 但是我必须刷新页面。 I tried adding something like 我尝试添加类似

$("#unapproved").append("<%= escape_javascript(render(:file => 'business')) %>");

but that just breaks it. 但这打破了它。

My guess (because your "submit" button isn't in the HTML above is that your "business_submit" button is just an input and not a submit button. 我的猜测(因为您的“提交”按钮不在上面的HTML中,是您的“ business_submit”按钮只是输入而不是提交按钮。

This code: 这段代码:

jQuery.fn.submitWithAjax = function() {
    this.submit(function() {
        $.post(this.action, $(this).serialize(), null, "script");
        return false;
    })
    return this; };

doesn't tell the form to submit. 不告诉表单提交。 It says when "submit" occurs, go do something. 它说,当“提交”发生时,去做一些事情。

From the jQuery documentation , submit(fn) is used to "Bind a function to the submit event of each matched element. The submit event fires when a form is submitted." jQuery文档中 ,submit(fn)用于“将函数绑定到每个匹配元素的commit事件。当提交表单时,将触发commit事件。”

You're never actually submitting the form. 您实际上从未提交过表单。 I'm willing to bet (can't be sure because I don't have all the code) that is you change the submitWithAjax method to this: 我愿意打赌(不确定,因为我没有所有代码)是您将submitWithAjax方法更改为:

jQuery.fn.submitWithAjax = function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false; };

it should work. 它应该工作。 It's at least closer to what you're trying to do. 至少与您要执行的操作更接近。

Working! 工作! I just tried to mimic the railscast 136. I threw my table into a file called _unapproved.html.erb. 我只是试图模仿railscast136。我将表格扔到了一个名为_unapproved.html.erb的文件中。 In my index I replaced the table with: 在索引中,我将表替换为:

<div id="unapproved">
  <%= render :partial => "unapproved" %>
</div>

And then in my create.js.erb, I had: 然后在我的create.js.erb中,我有:

$("#unapproved").append("<%= escape_javascript(render(:partial => "unapproved")) %>");

Game over. 游戏结束。 GG! GG!

Is the .append just adding that literal string to your #unapproved div? .append是否只是将文字字符串添加到您的#unapproved div中?

The .append wants to append rendered html rather than the ERB code you are trying to use. .append想要附加渲染的html而不是您尝试使用的ERB代码。 What I do for this sort of thing is to use the render function in my controller so that the AJAX call gets the HTML that was rendered. 我要做的事情是在控制器中使用render函数,以便AJAX调用获取已渲染的HTML。

For instance in the controller; 例如在控制器中;

respond_to do |format|
  format.js { 
    render :partial => "menu", :layout => false and return
  }
end

And in the view; 并认为;

$("a.show_menu").click(function() {
  var url = $(this).attr('href');
  $.ajax({
      beforeSend      : function(request) { request.setRequestHeader("Accept", "text/javascript"); },
                      /* Included so Rails responds via "format.js" */
      success         : function(response) { $("#menu").empty().append(response); },
      type            : 'GET',
      url                 : url
  });
  return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM