使用 $.ajax 向 Rails 控制器发送请求
我正在使用 Rails 3 和 JQuery。
我有两个变量,我想将它们从 javascript 代码发送到控制器并渲染我的视图,以便它们具有变量的新值。
我在 javascript 中的请求如下所示:
function sendGPToServer(title, address) 14 {
var dataString = 'name=' + title + '&address=' + address;
$.ajax({
type: "GET",
url: "/search",
data: dataString,
success: function() {
alert("succeeded!");
}
});
在页面控制器(搜索操作所在的位置)中,我有
protect_from_forgery :except => [:search]
,所以它不应该是安全问题。
我得到“成功了!”消息,但 search 没有被调用。但是,如果我手动重新加载主页,变量的值就会根据我的需要填充到我的网站页面中。
有谁知道为什么会发生这种情况?难道是因为我的 javascript 包含在我的 html 布局的标题中?
(另外:在routes.rb中,我已将pages/search更改为search,所以这应该不是问题)
谢谢
I am using Rails 3 with JQuery.
I have two variables, which I want to send from my javascript code to the controller and render my views so that they have new values of the variables.
My request in javascript looks like this:
function sendGPToServer(title, address) 14 {
var dataString = 'name=' + title + '&address=' + address;
$.ajax({
type: "GET",
url: "/search",
data: dataString,
success: function() {
alert("succeeded!");
}
});
In pages controller (where the search action lives) I have
protect_from_forgery :except => [:search]
so it shouldn't be security problem.
I get the "succeeded!" message but search does not get called. But if I reload the home page manually the values of the variables are filled in to my website page as I wanted.
Does anyone know why can this be happening? Can it be because my javascript is included to the header of my html layout?
(also: in routes.rb I have changed pages/search to search so it should not be a problem)
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不在成功回调函数中执行任何操作,为什么您期望变量被分配?
如果您执行了 success 函数,则意味着响应该 URL(使用 GET 请求)的方法已被调用,并且它已返回某些内容作为响应(也可能只是一个空的 HTTP 200)。
如果我是你,我会看看你的控制器方法返回什么以及如何在你需要的情况下使用它(fi 返回 json 并以某种方式使用它/渲染一些 js ...)
Why do you expect that your variables get assigned if you don't do anything inside the sucess callback function ?
If you have the success function executed it means that the method responding to that URL (with GET requests) has being called and it has returned something in response (maybe also just an empy HTTP 200).
If I was you I would have a look on what your controller method returns and on how to use it in the situation you need (f.i. returning json and use it somehow / render some js ... )