简体   繁体   中英

Sending an AJAX request to rails controller, then a HTTParty to external service, which returns JSON to output in .html.erb file

I am attempting to send an AJAX response to my rails controller, which will then send a HTTParty request to an external service. I am doing it this was because their would be a CORS issue if I sent a AJAX request straight from the JS. After the HTTParty, I need to receive the JSON it returns and output that on the .html.erb file. It seems complicated, but I just need a little bit of assistance implementing its functionality;

We begin by sending the AJAX request to our rails backend by doing the following.

$.ajax({
        url: "/gametitle",
        type: "post",
        data : {title: gametitle}
    });

The data send would look something like {"title": "AC3"}

This AJAX request would go to the routes file which looks like this:

   match '/gametitle' => 'loadtests#gametitle_post', via: :post

This route would then send it to the loadtest controllers gametitle_post method. Which looks like the following:

 def gametitle_post
    @gametitle = params[:title]
    HTTParty.post("http://supersecret.com/loadtests",
    :query => { :title => @gametitle })


    render nothing: true
 end

This is meant to receive the AJAX request, store the param sent, and then send a HTTParty request to receive JSON. But this is where I am stuck at the moment. Whenever I try to output the variable in @gametitle by console.log('<%= @gametitle %> it is an empty string.

Thank you for any help that you can give me in assisting me with this problem.

 def gametitle_post @gametitle = params[:title] @some_variable = HTTParty.post("http://supersecret.com/loadtests", :query => { :title => @gametitle }) //Access @some_variable in your view return end 

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