jQuery的岗位滑轨 [英] jQuery post to Rails

查看:131
本文介绍了jQuery的岗位滑轨的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的设置:Rails的3.0.9,红宝石1.9.2,jQuery的1.6.2

My setup: Rails 3.0.9, Ruby 1.9.2, jQuery 1.6.2

我有一个表格,显示多张照片和评论的用户,我希望实现内联注释。

I have a form that shows multiple photos and comments for a user and I wish to implement inline commenting.

<div id="newsfeed">    
 <div> 
 <div class="photo_title">Summer 2011</div> 
 <div class="newsfeed_photo"> 
 <a href="..." /></a> 
 </div> 
 <textarea class="comment_box">Write a comment...</textarea>  
</div> 
<div> 
 <div class="comment_title">Seeing a movie</div> 
 <textarea class="comment_box">Write a comment...</textarea>  
</div> 

我想在击中textarea的字段中输入密钥的用户提交一个AJAX职位。下面是JavaScript的(不完全)是我到目前为止

I want to submit an AJAX post upon the user hitting the enter key in the textarea field. Here's the javascript (incomplete) that I have so far

  $('#newsfeed').delegate('.comment_box', 'keydown', function (event){
    event.preventDefault();
    $.post('/sub_comments', ...);
  });

我使用了代理的方法,因为&LT; D​​IV ID ='新闻推送'&GT; 内容可能是与其他AJAX调用替换。我需要的是语法的jQuery 方法,假设我需要通过某种形式的PARAMS喜欢说 photo_id 等。假设我有一个方法来访问值的参数,可以有什么语法来电创造PARAMS Rails的期望它们的方式

I'm using the delegate method because <div id='newsfeed'> contents could be replaced with another AJAX call. What I need is the syntax for jQuery post method assuming I need to pass some form params like say photo_id, etc. Assume that I have a way to access the values for the params, what's the syntax for the post call to creating params the way Rails expect them

下面是标准的Rails位

Here's the standard Rails bits

sub_comments_controller.rb

  def new
    @sub_comment = SubComment.new

    respond_to do |format|
      format.html # new.html.erb
      format.js
    end
  end

此外,我不希望使用通常的&LT;%=的form_for(@sub_comment,:远程=&GT;真)办| F | %&GT; 为每一位行内的评论,我可以补充。我还简要地介绍了瑞安贝茨的 railscast 但code看起来过时的。

Also I don't want to use the usual <%= form_for(@sub_comment, :remote => true) do |f| %> for each and every inline comment I could add. I have also taken a look at Ryan Bates's railscast but the code looks outdated.

推荐答案

您可以设置您的文章,只要它是在铁轨上结束正确PTED除$ P $,但最好的做法是为组织数据以任何方式具有模型名'的对象与所有的值。

You can setup your post to structure the data in any way as long as it is interpreted correctly on the rails end, but best practice is to have an object of 'model-name' with all the values.

Javascript的

$.ajax({
    url: "/sub_comments",
    type: "POST",
    data: {subcomment: {
             field: val, 
             field2: val, etc... }},
    success: function(resp){ }
});

的Rails

def create
  @sub_comment = SubComment.new params['subcomment']
  if @sub_comment.save
    render :json => { } # send back any data if necessary
  else
    render :json => { }, :status => 500
  end
end

这篇关于jQuery的岗位滑轨的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆