gpt4 book ai didi

javascript - 如何使用 AJAX 将 JS 变量传递给 Controller ​​?

转载 作者:行者123 更新时间:2023-11-28 01:28:20 24 4
gpt4 key购买 nike

如何使用 AJAX 将 JS 变量传递给 Controller ​​?

我正在使用 Ruby 2.0 和 Rails 4。

我需要将JS函数获得的某些JS变量的值传递给 Controller ​​,以将其添加为数据库中的记录,我目前正在使用多个数据表来显示信息,用户在数据表中选择一行,然后按下一个按钮,然后获取所选行的 id 并将其作为行和显示的另一个数据表添加到数据库中的表中,问题是我既不想使用表单,也不想刷新页面,而且所有这些所呈现的信息是在启动时加载到 View 中的,我在每个步骤(数据表)中都会“预保存”选择,而用户不知道。

现在我可以获取 View 中所选行的值,然后将其呈现在隐藏字段中,我需要获取 Controller 中隐藏字段的值

我读过 AJAX 可以完成这项工作,但我以前没有使用过 ajax。

一些代码:

script.js(咖啡中)

leaveAStepCallback =(obj, context) ->
alert("Leaving step " + context.fromStep + " to go to step " + context.toStep);
ret=false
if (context.fromStep==1 and context.toStep==2)
document.getElementById('selec1').value= fnGetIdsOfSelectedRows fnGetSelected(oTable1), oTable1 #//get selected rows
ret=true

some_controller.rb中需要一些像:

def pre_save
if params[:step]=='1' #hidden_Field with step number
@selrow=params[:selec1].to_s.split(',') #selected rows as '1,2,5,7'
i=0
while i<@selrow.length
pr=@selrow.at(i).to_i #selected row number

addp=PreSaveTable.new #table to record each selected row
addp.id_row=pr
addp.save #save as row in table
i=i+1
end

end

end

有什么帮助吗?

最佳答案

I've not worked with ajax before

让我解释一下:

<小时/>

Asynchronous Javascript & XML

Ajax 请求通过 Javascript 等技术发送,以将请求发送到典型 HTTP 请求范围之外的服务器。这意味着您可以创建伪“实时”功能——无需刷新

使用 ajax 特别简单 JQuery :

$.ajax({
url: "your_endpoint",
data: "your_serialized_data",
success: function(data) {
//code on success
},
error: function(data) {
//code on error
}
});
<小时/>

代码

#javascript
$(document).on("event", "element", function(e){
$.ajax({
url: "controller/action",
data: $("hidden_field").val().serialize()
});
});

#controller
def pre_save
if params[:step] == '1' #hidden_Field with step number
@selrow = params[:selec1].to_s.split(',') #selected rows as '1,2,5,7'
i=0
while i < @selrow.length
pr=@selrow.at(i).to_i #selected row number

addp=PreSaveTable.new #table to record each selected row
addp.id_row=pr
addp.save #save as row in table
i=i+1
end

respond_to do |format|
format.html
format.js #-> loads views/controller/pre_save.js.erb
end

end

#app/views/controller/pre_save.js.erb
alert("Presave Complete!");

关于javascript - 如何使用 AJAX 将 JS 变量传递给 Controller ​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22445127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com