[英]Ruby on Rails rendering via an ajax call doesn't work as expected
我通過ajax調用將某些內容加載到內容div中時遇到問題。
我的應用程序中包含以下代碼的ChangeAvatarController。
class ChangeAvatarController < ApplicationController
before_action :authenticate_user!
def index
render '_index', :layout => false
end
end
end
在我的dashboard.html.erb中,我有以下div
<div id="content">
</div>
我有以下代碼
應用程序/視圖/ change_avatar / _index.html.erb:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
和app / view / change_avatar / _index.js.erb
$("#content").html("<%= escape_javascript(render 'index')%>");
我的rooutes.rb中有以下路線
get 'change_avatar/index'
所以,
當我通過以下方式呈現index.html.erb時,它是完美的:
<div id="content>
<%= render 'change_avatar/index', remote: true %>
</div>
名:約翰
姓氏:Doe
全名:約翰·杜
但是,當我使用以下方式時,
<script>
$.ajax({
url: "/change_avatar/index",
type: 'GET',
cache: false,
success: function(html){
$("#content").append(html);
}
})
</script>
<div id='content'>
</div>
我得到這個:
名字:
姓:
全名:{{firstName +“” + lastName}}
javascript調試控制台中沒有錯誤。
我不知道是什么問題,
有什么建議么,
謝謝。
<script>
$.ajax({
url: "/change_avatar/index",
type: 'GET',
cache: false
})
</script>
因為我假設您有一個帶有以下內容的changeavatars / index.js.erb文件,就足夠了:
$("#content").append("<%= escape_javascript(render 'changeavatars/index') %>")
另外,您應該在控制器中將render '_index'
更改為render :index
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.