使用ajax或jQuery在ruby on rails上更新数据库

update data base on ruby on rails using ajax or jQuery

本文关键字:rails 更新 数据库 on ruby ajax jQuery 使用      更新时间:2023-09-26

我有一个文本字段输入,它包含数据库属性(ref)的值。正如你可以从代码中注意到的,当我把注意力集中在文本字段上时,边框会出现,当点击退出时,边框会消失。

我的问题是,当我点击,我希望文本字段中的数据将存储在数据库中没有提交按钮。

<script>
$(document).ready(function(e){
    $('.class1').focusin(function(){
        $(this).attr('readonly',false);
        $(this).css('border','1px black solid');
    })
    $('.class1').focusout(function(){
        $(this).attr('readonly',true);
        $(this).css('border','0px white solid');
    })
} );
</script> 
<div>Ref: <%= text_field_tag(:ref,@ref.to_s,:readonly=>true, :class => "classe1" )%>  </div>

如何将值发送到我的应用程序?

要更新特定的记录,只需使用jquery为该输入字段或文本框调用blur函数。使用类名或输入字段的id调用blur函数。

$('#ref').blur(function() {
    update_ref_field();
});

JS函数调用ajax:

function update_ref_field(){
    var ref_value = $('#ref').val();
    var url = '/controller_name/action_name/?ref='+ref_value;
    $.ajax({
       type: 'put',
       url: url,
       dataType: "jsonp",  
       // You can use this jsonp if your request related to cross domain
       error: function (result, status, xhr){
            alert('result='+result+'::status='+status+'::xhr= '+ xhr);
            alert('Error occurred while updating the record.');           },
       success: function(result, status, xhr){
           alert('result='+result+'::status='+status+'::xhr= '+ xhr);
           alert('Record updated successfully.');
    });
    return false;
}
<<p> 更新代码/strong>
function update_ref_field(){
  var ref_value = $('#ref').val();
  var url = '/controller_name/action_name/?ref='+ref_value;
  $.ajax({
    type: 'post',
    url: url,
    dataType: 'script',
    error: function(data){
      alert('Error occurred while updating the record.');
    }, 
    success: function(data){
      alert('Record updated successfully.');
    });
    return false;
}

发送ajax请求:http://api.jquery.com/jQuery.ajax/。如果记录存在并且您正在更新它,则将"类型"设置为"PUT",如果是新记录则设置为"POST"。发送这个的url很可能是控制器的名称我想你们没有提供。如。"/控制器"。

的例子:

$.ajax({
  type: "POST",
  url: "/controller",
  data: {ref: $('.classe1').html().trim()}
});

如果你不能让它工作,你需要提供一些关于你正在使用的rails代码的更多信息,我做了一些一般的猜测。

这是我的代码:
视图:

    <script> 
     function update_ref_field(){
     var ref_value = $('#ref1').val();
     var url = '/ModController/update_ref_field/?ref1='+ref_value;
    $.ajax({
        type: "POST",
        url: url,
        //dataType: "jsonp",
        // You can use this jsonp if your request related to cross domain
        error: function (result, status, xhr){
            alert('result='+result+'::status='+status+'::xhr= '+ xhr);
            alert('Error occurred while updating the record.');           },
        success: function(result, status, xhr){
            alert('result='+result+'::status='+status+'::xhr= '+ xhr);
            alert('Record updated successfully.');
        }});
       return false;
       }

        $('#ref1').focusin(function(){
            $(this).attr('readonly',false);
            $(this).css('border','1px black solid');
        })
        $('#ref1').focusout(function(){
            $(this).attr('readonly',true);
            $(this).css('border','0px white solid');
            $javascript:update_ref_field();

    })
} );

控制器上的

:
def update_ref_field ()
开始
@projj=Project.find(params[:project_id]) # project courant
@local_date = Time.new().to_date
@sem = caluculer_semaine(@local_date)
@existe_mom_pour_cet_semaine = Mod.find(:all,:conditions => {:project_id => @projj。Id,:semaine => @ semaine})
#ce对应UN更新
开始
@existe_mom_pour_cet_semaine。Each do |a|
如果(params [: ref1 ]) != " || ( params [: ref1]) ! = nil
A.update_attributes (:ref => params[:ref1])

结束如果a.save
Flash [:notice] ="mise a jour de ref "
其他
Flash [:error] ="mise ajour for ref about "

结束
结束rescue Exception => e
把e.message
把e.backtrace.inspect

结束redirect_to: action =>"团聚"

结束结束

当我使用tag_form时,我工作正常,但我希望数据库上的变化将在后台
由于

谢谢大家的帮助。
这个问题的解决方案是使用一个javascript函数来调用控制器中的另一个函数

 function loadXMLDoc(id, val, name)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            //document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            alert();
        }
    }
            //update_ref_field => methode in the contoller with complete the update in the data     base
            xmlhttp.open("GET","update_ref_field?ref1="+val ,true);
            xmlhttp.send();

}