简体   繁体   English

Rails-通过AJAX进行HTTParty请求

[英]Rails - HTTParty request through AJAX

I am new to both Rails and AJAX. 我是Rails和AJAX的新手。 I want to consume an API which is hosted on a different website. 我想使用一个托管在其他网站上的API。 I ran into problems with cross origin HTTP request. 我遇到跨源HTTP请求的问题。 So I tried doing this by using HTTParty. 因此,我尝试使用HTTParty进行此操作。

In the code below, I am setting the text of $(".result") as JSON.parse(HTTParty()) request, so that it can query the website and give me the result. 在下面的代码中,我将$(“。result”)的文本设置为JSON.parse(HTTParty())请求,以便它可以查询网站并给我结果。

Rails code: Rails代码:

<%= form_for(@profile) do |f| %>
  <%= f.label :content %>
  <%= f.text_field :content, class: 'ajax-control' %>
  <%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>

<p class="result"></p>

Javascript code: JavaScript代码:

<script>
  $(document).ready(function(){

    $('.ajax-control').on('keyup',function(){
       var charCount = $(this).val().length;
       if(charCount===3){
        var str1='<%=JSON.parse(HTTParty.get("http://example.com/api.php?param='+$(this).val()+'"))%>'
        $(".result").text(str1);
       }
    });
  });
</script>

Now comes the weird problem. 现在出现了奇怪的问题。 The code above does send the GET request to example.com (placeholder), but gets a response saying that it is not a valid query. 上面的代码确实将GET请求发送到example.com(占位符),但是得到了一个响应,指出它不是有效的查询。

However, if I pass the str1 as follows - 但是,如果我按如下方式通过str1:

var str1='<%=JSON.parse(HTTParty.get("http://example.com/api.php?param=xyz"))%>'
 $(".result").text(str1);

I get the expected response. 我得到了预期的答复。 If the $(".ajax-control") text field is "xyz", I get a response saying not a valid query. 如果$(“。ajax-control”)文本字段为“ xyz”,则会收到响应,指出无效查询。

Does string concatenation in javascript introduces new characters because of which it is throwing an error? javascript中的字符串连接是否会引入新字符,因此会引发错误?

That javascript (which in turn has ruby code via erb) is not going to execute after its been rendered the first time by Rails. 在由Rails首次渲染后,该javascript(反过来通过erb具有ruby代码)将无法执行。

That is, its not going to be invoked each time that keypress callback is called, which means that when Rails is rendering that Javascript it obviously has no knowledge of the client-side DOM so the URL is affectively: 也就是说,它不会在每次按键回调被调用时都被调用,这意味着当Rails呈现Javascript时,它显然不了解客户端DOM,因此该URL是有效的:

JSON.parse(HTTParty.get("http://example.com/api.php?param="))

And the remote server has an empty param which it doesnt like... 而且远程服务器有一个空的param ,它不喜欢...

If you really need to invoke that API for every keypress you have two options: 如果确实需要为每次按键调用该API,则有两个选择:

  1. Get it to work via Ajax using CORS 使用CORS通过Ajax使其正常工作
  2. Invoke an endpoint in your Rails app, which in turn uses Ruby-side HTTParty to invoke the API and relay the response back to the client. 在Rails应用程序中调用一个端点,该应用程序随后使用Ruby端的HTTParty调用API,并将响应中继回客户端。

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

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