简体   繁体   English

通过Rails和AngularJS中的AJAX调用打印JSON数据

[英]Print JSON data through AJAX call in Rails and AngularJS

New to Rails, I have a Ruby application in my home_controller.erb which returns a JSON value from MongoDB and I have stored in @tuple Variable. Rails的新手,我的home_controller.erb中有一个Ruby应用程序,它从MongoDB返回JSON值,并且存储在@tuple Variable中。

How can I print the JSON response on the Front end. 如何在前端打印JSON响应。 Any help would be great. 任何帮助都会很棒。

tuple={"_id":{"$oid":"565a8bf88ab8dc1cc6000006"},"zip":"85009"} tuple = {“ _ id”:{“ $ oid”:“ 565a8bf88ab8dc1cc6000006”},“ zip”:“ 85009”}

This is my controller code: 这是我的控制器代码:

  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

My index.html.erb file: 我的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>

Usually add 通常添加

render json: @data_to_be_printed

as the last line of your index action will return JSON structure as you expected. 因为index操作的最后一行将按预期返回JSON结构。

Usually, the path in ajax should be the path in route.rb, please also check the route first 通常,ajax中的路径应该是route.rb中的路径,也请先检查该路径

In your index.html.erb 在您的index.html.erb中

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

and add 并添加

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

in the index action of this home controller -- home_controller.rb 在此家庭控制器的索引动作中-home_controller.rb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM