【问题标题】:Ajax Single Field Submission in form表单中的 Ajax 单字段提交
【发布时间】:2012-03-06 13:52:20
【问题描述】:

我创建了一个订单表单,其中包含大量字段。我现在正在添加优惠券功能,以便我们可以开始为客户提供折扣代码等。

单击“应用优惠券”按钮后,使用 ajax 提交单个字段(优惠券代码)的最佳方式是什么,以便可以使用 UJS(?)在前端更新价格 - 显然是最终的价格计算会在后端进行吗?

干杯。

【问题讨论】:

    标签: ruby-on-rails ajax ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    我建议使用 JS 框架来执行 Ajax 请求。如果你是 JQuery,那么你可以使用给出的例子来了解如何做一个simple post。

    <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
      <form action="/" id="searchForm">
       <input type="text" name="s" placeholder="Search..." />
       <input type="submit" value="Search" />
      </form>
      <!-- the result of the search will be rendered inside this div -->
      <div id="result"></div>
    
    <script>
      /* attach a submit handler to the form */
      $("#searchForm").submit(function(event) {
    
        /* stop form from submitting normally */
        event.preventDefault(); 
    
        /* get some values from elements on the page: */
        var $form = $( this ),
            term = $form.find( 'input[name="s"]' ).val(),
            url = $form.attr( 'action' );
    
        /* Send the data using post and put the results in a div */
        $.post( url, { s: term },
          function( data ) {
              var content = $( data ).find( '#content' );
              $( "#result" ).empty().append( content );
          }
        );
      });
    </script>
    
    </body>
    </html>
    

    【讨论】:

    • Rails 中是否没有等效的 link_to(带有 post 参数)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2017-02-03
    • 2014-02-19
    • 2011-05-09
    • 1970-01-01
    相关资源
    最近更新 更多