[英]Print JSON data through AJAX call in Rails and AngularJS
Rails的新手,我的home_controller.erb中有一個Ruby應用程序,它從MongoDB返回JSON值,並且存儲在@tuple Variable中。
如何在前端打印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>
通常添加
render json: @data_to_be_printed
因為index
操作的最后一行將按預期返回JSON結構。
通常,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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.