Rails in place edit with jQuery

Posted by wxianfeng Tue, 13 Oct 2009 16:43:00 GMT
环境 : ruby 1.8.6 + rails 2.1.0 + jquery 1.3.2

效果:

http://www.appelsiini.net/projects/jeditable/default.html

http://15daysofjquery.com/examples/jqueryEditInPlace/divEdit.php

像上面的这种 in place edit 的效果在网络上很常见。。下面介绍一种在rails中的解决方案。。当然后台不一定是 ror 平台了

资源下载:

http://github.com/tuupola/jquery_jeditable 下载后,只需要里面的 jquery.jeditable.js 步骤:

1,加载 jquery.js 和 jquery.jeditable.js

2,View

<script>
  $(document).ready(function() {
    $(".edit_descrip").editable(this.href, {
      indicator : "<img src='/images/indicator.gif'>",
      type   : 'textarea',
      submitdata: { _method: "get" },
      select : true,
      submit : '修改',
      cancel : '取消',
      cssclass : "editable",
      tooltip   : '点击修改',
      id   : 'flag'
    });
  });
</script>
<p  class="edit_descrip" id="edit_descrip" onmouseover="this.style.backgroundColor='yellow'" onmouseout="this.style.backgroundColor='white'"><%= h @client_info.description %> </p>
默认向后台发送的是id 和 value 两个参数,值分别是p对应的id 和 p对应的内容,当然你也可以改变参数名字
id : 'flag'
value : 'newvalue'
就对应传递 flag 和 newvalue 两个参数 了

3,Controller:
if request.xhr?
  if params[:flag]       
        case params[:flag]
        when 'edit_descrip'   
          ClientInfo.update_field(current_client_info.id,params[:value],'descrip') # 更新数据库
          render :text => params[:value] #返回数据
    end
  end
end
4,改变一些默认的参数,可以到 jquery.jeditable.js 中修改,例如 textarea 的默认大小 等等。。。。

5,或者你可以指定target为某个函数,这样就可以自己扩展,例如有额外的返回数据,返回后需要更新某个 DOM元素等等

 <script>
    $(document).ready(function() {
      $(".edit_state").editable(submitEdit, {
        indicator : "<img src='/images/indicator.gif'>",
        type   : 'textarea',
        submitdata: { _method: "get" },
        select : true,
        submit : '修改',
        cancel : '取消',
        cssclass : "editable",
        tooltip   : '点击修改',
        id   : 'flag'
      });
    });

    function submitEdit(value, settings)
    {
      var edits = new Object();
      edits[settings.name] = [value];
      edits[settings.id] = ['edit_state']
      $.ajax({
        url: this.href,
        type: "GET",
        data : edits,
        dataType : "json",
        complete : function ()
        {
          $("#state_time").html('0分钟前');
        }
      });
      return value;
    }

  </script>
See:

http://www.appelsiini.net/projects/jeditable

http://stackoverflow.com/questions/966539/how-to-get-out-of-jquery-jeditable-mess

This entry was posted on Tue, 13 Oct 2009 16:43:00 GMT and Posted in , . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.

Tags


Trackbacks

Use the following link to trackback from your own site:
http://wxianfeng.com/trackbacks?article_id=5

Comments

Leave a comment