简体   繁体   中英

Unable to Parse JSON Response from Rails Controller in Javascript

I'm working in a Rails 4 app and using best_in_place AJAX to update a user's address field.

The AJAX call works successfully and in my update action in my controller I have a respond_to block that I'd like to spit out the user id, the new updated address and a boolean for if the address is valid or not.

respond_to do |format|
  format.json { render :json => { :id => @user.id, :address => @user.address, :address_valid => @user.address_valid } }
end

In my Javascript, I'm trying to parse that JSON. I have tried both ['id'] and dot notation. Here's my JS function to listen for the JSON after a successful update:

$('.best_in_place').bind("ajax:success", function (response, data) {
    console.log(response)
    console.log(data)
    console.log(typeof data)
  });
});

The console logs the response as well as the JSON from the controller predictably:

jQuery.Event {type: "ajax:success", timeStamp: 1401820902436, jQuery1110046177322673611343: true, isTrigger: 3, namespace: ""…}
{"id":704,"address":"Austin, TX 78751, USA","address_valid":false} 
string

I'm getting 'undefined' for data.id. I've also tried calling ## Heading ##

So I had already typed up my question but I figured I'd post because I found the answer and figured it might help someone: I needed to use

JSON.parse() 

in my JS and set the JSON object to a variable. From there, I was able to access the JSON object.

var user = JSON.parse(data) 

From there, I was able to call user.id, user.address, etc. in my JS.

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