简体   繁体   中英

Rendering JSON from AJAX call in Rails

I have an ajax call to fetch information from Flickr API which returns JSON data. I want to display values from JSON data in my view. I do this by editing some innerHTML with jQuery. The problem I am having is that the data is undefined, so it looks like a scoping problem.

photo.js

jQuery(function() {
  $('#<%=p[:id]%>').click(function (e) {

    //ajax call to fetch photo info

    var fetch_id = '<%=p[:id]%>';
    var fetch_secret = '<%=p[:secret]%>';  

    $.ajax({
      type: 'GET',
      url: '/photos/fetch_info',
      dataType: 'json',
      data: { 'id' : fetch_id, 'secret' : fetch_secret },
      success: function(data){

        console.log(data)  //returns Object
        console.log(data.title)  //returns appropriate title

        //edit innerHTML of basic_modal
        $('.basic_modal').html(
          "<div id='modal_image'><%= escape_javascript(image_tag p[:url]) %></div><div id='photo_title'><%=data.title %></div>"
         );

        //load modal
          $('.basic_modal').modal({
          overlayClose:true
        });

      } //end success: function(result)
    });

When I print data.title to console, I get the appropriate title. However, when I try to edit HTML and render <%=data.title %> , I get an undefined variable/method error.

Any tip on how I can display the data in my modal in the view?

Here is my controller:

def fetch_info

  @info = flickr.photos.getInfo(:photo_id => params[:id], :secret=> params[:secret])

  respond_to do |format|
    format.json { render :json => @info }
  end

end
 var result = jQuery.parseJSON(data);

You donot need to do this, Because datatype:JSON already parse the data

$('.basic_modal').html(
          "<div id='modal_image'><%= escape_javascript(image_tag p[:url]) %>
</div><div id='photo_title'><%="+data.title+" %></div>"
         );

this might help you

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