Php 使用ajax检查Rails中的变量
我是RubyonRails的新手,我想知道一个与我使用PHP所做的事情相当的Rails 在检查用户输入是否符合某些标准时,我通常使用javascript对处理数据并回显json数据的php页面进行一些Ajax调用。然后,我使用json数据来构造适当的行为 例如,假设一个用户提交了一个邮政编码,我想在服务器端对邮政编码进行一些检查。在js中,我会这样做:Php 使用ajax检查Rails中的变量,php,ruby-on-rails,ruby,ajax,Php,Ruby On Rails,Ruby,Ajax,我是RubyonRails的新手,我想知道一个与我使用PHP所做的事情相当的Rails 在检查用户输入是否符合某些标准时,我通常使用javascript对处理数据并回显json数据的php页面进行一些Ajax调用。然后,我使用json数据来构造适当的行为 例如,假设一个用户提交了一个邮政编码,我想在服务器端对邮政编码进行一些检查。在js中,我会这样做: // This is what the user submitted var postcode = $("#postcode").val();
// This is what the user submitted
var postcode = $("#postcode").val();
// Here, I post it to a PHP file
// PHP file examines the data and returns result
// (in this case, if the postcode is covered or not)
$.post("scripts/postcode_handling.php", {postcode: postcode}, function(data) {
var result = jQuery.parseJSON(data);
// Check the coverage
if (result.coverage == true) {
// Do Something
} else {
// Do something
}
在php文件中,我将执行以下操作:
...
$result = array('coverage' => false , 'message' => "Your postcode is not covered")
echo json_encode($result);
....
我试图在Rails中做一些类似的事情,用控制器下的一个动作替换php文件,但我想不出来。这在Rails中是一种常见的做法吗?我怎样才能做到这一点呢?让我们使用您的post代码示例。假设您想要基于邮政编码进行地址查找
config/routes.rb
并添加一个路由:
resources :address_lookups, only: :new
创建控制器以处理路由:
rails g controller AddressLookups
上面的命令在app/controllers
内部创建一个名为address\u lookups\u controller.rb的新控制器
现在在控制器内添加必要的逻辑以处理地址查找:
class AddressLookupsController < ApplicationController
def new
# This action will expect a params[:post_code] variable
# that you will pass with your ajax request
post_code = params[:post_code]
address = FindSomeAddress.lookup(post_code)
render json: address
end
end
发布您在rails控制器中尝试的内容。可能会将format::json
添加到路由中,这样它就不会尝试呈现html,也不会找到视图。同样,我会使用$.getJSON
而不是$.ajax
。谢谢。你的解决方案非常有效。最后,我在控制器中执行了如下操作:render html:1 if PostcodeCoverage.exists?(:postcode=>@postcode)
。@MikeC您可能需要使用render plain:“OK”
,因为您正在渲染一个数字(“OK”可以是您想要的任何东西)@穆罕默德,谢谢你。这个链接非常有用。
jQuery ->
$('#post_code').on 'blur', ->
field = $(this)
post_code = field.val()
if post_code.length is 8
xhr = $.ajax
url: "/address_lookups/new"
data:
post_code: post_code
success: (data) ->
# do something with data
dataType: "json"