[英]ajax get data from a rails controller
I am trying to use ajax to get information from my controller. 我正在尝试使用ajax从控制器获取信息。 Basically I want to know if a data already exists in the DB or not, so my controller will return either true or false.
基本上,我想知道数据库中是否已经存在数据,因此我的控制器将返回true或false。 At the moment I am just trying to set the basic ajax call
目前,我只是尝试设置基本的ajax调用
in my js file I have the following ajax call, as you can see at the moment I am not really doing any logic because my data is just a placeholder. 在我的js文件中,我有以下ajax调用,如您所见,由于我的数据只是一个占位符,因此我目前并未真正执行任何逻辑。 Later I will add the information I want to query
稍后我将添加我要查询的信息
$.ajax({
type: "GET",
url: "/locations/exists",
dataType: "JSON",
data: { 'locition_exist': loc_exit },
success: function(data) {
console.log(data);
}
});
In my controller I have 在我的控制器中
def exists
location_exists = true
respond_to do |format|
format.html
format.json {render json: location_exists }
end
end
Later value will go into a method in the model that will query the DB and return true/false. 稍后的值将进入模型中的方法,该方法将查询数据库并返回true / false。
In my routes I have 在我的路线中,
resources :locations
get 'locations/exists', to: 'locations#exists'
This code results in the following error 此代码导致以下错误
The action 'show' could not be found for LocationsController
I am new to rails and ajax , and I based my code on different examples that I read here, so I am probably just doing a stupid noob mistake. 我是Rails和Ajax的新手,并且我的代码基于在这里阅读的不同示例,因此我可能只是在犯一个愚蠢的noob错误。 Thank you very much for your help
非常感谢您的帮助
When using get
or match
in routes, you need to define the controller method mapped 在路由中使用
get
或match
时,需要定义映射的控制器方法
get 'locations/value', to: 'locations#value'
update 更新
You saw the same error after updating routes. 更新路由后,您看到了相同的错误。 There are two reasons of this error:
此错误有两个原因:
You defined resources :location
at first. 您首先定义
resources :location
。 The url locations/exists
itself matches "show" method within resources, with Routes taking 'exists'
as the id in #show
. 网址
locations/exists
本身本身与资源中的“显示”方法匹配,而Routes在#show
中将'exists'
作为id。
You have not defined show
within LocationsController 您尚未在LocationsController中定义
show
So, Routes will firstly map the url to locations#show
with the :id
as 'exists'
, then hits the controller and found #show
does not exist. 因此,Routes将首先将URL映射到带有
:id
为'exists'
locations#show
,然后命中控制器并发现#show
不存在。
The solution after your updating 更新后的解决方案
Of course you can put get 'exists'...
before resources but that looks ugly. 当然,您可以在资源之前放置
get 'exists'...
但这看起来很丑。
Since 'exists'
requires no id, it is a collection method. 由于
'exists'
不需要ID,因此它是一种收集方法。 So you can use Routes built-in ways to do that. 因此,您可以使用内置的Routes方法来执行此操作。
resources :locations do
collection do
get 'exists'
end
end
By this all your resources and 'exists' can live. 这样,您所有的资源和“存在”都可以生存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.