【问题标题】:Print JSON data through AJAX call in Rails and AngularJS在 Rails 和 AngularJS 中通过 AJAX 调用打印 JSON 数据
【发布时间】:2015-11-29 05:42:20
【问题描述】:

Rails 新手, 我的 home_controller.erb 中有一个 Ruby 应用程序,它从 MongoDB 返回一个 JSON 值,我存储在 @tuple 变量中。

如何在前端打印 JSON 响应。任何帮助都会很棒。

tuple={"_id":{"$oid":"565a8bf88ab8dc1cc6000006"},"zip":"85009"}

这是我的控制器代码:

  class HomeController < ApplicationController

  def index



   uri='mongodb://heroku_bv2wfp7x:bt1uo8ddu73rs5p6b9nvk5tp4u@ds051534.mongolab.com:51534/heroku_bv2wfp7x'

   connection_variable=Mongo::Client.new(uri)


connection_variable[:mongoearthquakes].drop
puts "Connected to Mongo DataBase, Inserting data . . . . . "

$j=0

while $j < 9 do
// inserting data into MongoDB
    $j+=1
end



result=connection_variable[:mongoearthquakes].find()

result.each do |tuple|
    tuple=tuple.to_json

    puts tuple

    @data_to_be_printed=tuple
end


end

我的 index.html.erb 文件:

 <!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Hello world: </p>
</div>  

<script>

      angular.module('myApp', []).controller('myCtrl', ['$scope', '$http', function($scope, $http) {

    $.ajax({
        type: "GET",
        url: "@data_to_be_printed",
        dataType: "json",
        success: function(data){
        console.log(@data_to_be_printed) 
    }        
});

}]);
</script>
</body>
</html>

【问题讨论】:

标签: ruby-on-rails ruby angularjs json


【解决方案1】:

一般加

render json: @data_to_be_printed

index 操作的最后一行将按预期返回 JSON 结构。

【讨论】:

  • 我实际上在 URL 处遇到错误。 404 未找到错误。
  • 我是否以正确的方式从 Controller 访问 JSON 数据?
  • 我不认为这是正确的。如果您在本地环境中运行并且您的根路由在HomeController 中设置为index,则该网址应该类似于“localhost:3000
【解决方案2】:

通常ajax中的路径应该是route.rb中的路径,也请先查看路由

在你的 index.html.erb 中

$.ajax({
    type: "GET",
    url: <%= home_index_path %>+".json",  
    dataType: "json",
    success: function(data){
    }
}  

并添加

respond_to do |format|
  format.json  { render json: @data_to_be_printed }
end

在这个家庭控制器的索引动作中——home_controller.rb

【讨论】:

  • 那么,我的 URL 应该指向返回的 JSON 值吗?
  • 我想这就是你的目的。您应该能够通过命令rake routes 看到您的 home#index 路径
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 2019-07-11
  • 2017-12-27
  • 1970-01-01
相关资源
最近更新 更多