简体   繁体   English

将AJAX请求发送到rails控制器,然后将HTTParty发送到外部服务,该服务返回JSON以在.html.erb文件中输出

[英]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. 我试图将AJAX响应发送到我的rails控制器,然后它将HTTParty请求发送到外部服务。 I am doing it this was because their would be a CORS issue if I sent a AJAX request straight from the JS. 我这样做是因为,如果我直接从JS发送AJAX请求,那么这将是CORS问题。 After the HTTParty, I need to receive the JSON it returns and output that on the .html.erb file. 在HTTParty之后,我需要接收它返回的JSON并将其输出到.html.erb文件中。 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请求发送到我们的rails后端。

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

The data send would look something like {"title": "AC3"} 发送的数据类似于{“ title”:“ AC3”}

This AJAX request would go to the routes file which looks like this: 此AJAX请求将转到路由文件,如下所示:

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

This route would then send it to the loadtest controllers gametitle_post method. 然后,此路由会将其发送到loadtest控制器gametitle_post方法。 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. 这旨在接收AJAX请求,存储发送的参数,然后发送HTTParty请求以接收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. 每当我尝试通过console.log('<%= @gametitle %>输出@gametitle的变量时,它都是一个空字符串。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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