简体   繁体   中英

Unable to parse JSON from Rails server with Javascript

I am trying to parse the JSON data rendered from my Rails server with Javascript, however I keep facing an unknown error. I am just starting out with JS, but have good experience with Rails.

It would be great if someone could point me in the right direction! Chrome控制台

EDIT: Added code I'm trying to use React with my Rails application. And when I try to parse the JSON data, the server crashes, so that's why I tried to debug in the console and faced the same error.

Here's my view,

<%= react_component "SongsContainer", { songsPath: songs_path } %>

And here's my React code,

var SongsContainer = React.createClass({
componentWillMount(){
    this.fetchSongs();
    setInterval(this.fetchSongs, 1000);
},

fetchSongs() {
    $.getJSON(
        this.props.songsPath,
        (data) => this.setState({songs: data});
    );
},

getInitialState() {
    return { songs: [] };
},

render() {
    return <Songs songs={this.state.songs} />;
}
});

And my controller is very basic,

render :json => Song.first.to_json

EDIT: Error when trying to use getJSON, 在此处输入图片说明

It seems that the error is not in the invocation but rather in the syntax. according to getJSON jquery documentation you should pass the data as a string.

Have you tried passing the argument this way?

fetchSongs() {
    $.getJSON(
        this.props.songsPath,
        this.setState({songs: data})
    );
}

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