简体   繁体   中英

Ruby on Rails rendering via an ajax call doesn't work as expected

I have an issue with loading some content into a content div via an ajax call.

I have ChangeAvatarController in my application with the following code.

class ChangeAvatarController < ApplicationController

    before_action :authenticate_user!

    def index
       render '_index', :layout => false
    end
  end
end

And in my dashboard.html.erb I have the following div

<div id="content">

</div>

I have the following piece of code

app/view/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>

And app/view/change_avatar/_index.js.erb

$("#content").html("<%= escape_javascript(render 'index')%>");

I have the following route in my rooutes.rb

get 'change_avatar/index'

So,

When I render the index.html.erb with the following way It's perfect:

<div id="content>
    <%= render 'change_avatar/index', remote: true %>
</div>

First Name: John

Last Name: Doe

Full Name: John Doe

However, when I use the following way,

<script>
    $.ajax({
       url: "/change_avatar/index",
       type: 'GET',
       cache: false,
       success: function(html){
           $("#content").append(html);
       }
    })
</script>

<div id='content'>


</div>

I get this one:

First Name:

Last Name:

Full Name: {{firstName + " " + lastName}}

There is no error in javascript debug console.

I can't figure out what the problem is,

Any suggestions,

Thanks.

<script>
    $.ajax({
       url: "/change_avatar/index",
       type: 'GET',
       cache: false
    })
</script>

Would suffice since I'm assuming you have a changeavatars/index.js.erb file with:

  $("#content").append("<%= escape_javascript(render 'changeavatars/index') %>")

Also, you should change render '_index' in your controller to just render :index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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