【问题标题】:What's the rails way to post form data to a third party web service?将表单数据发布到第三方 Web 服务的 Rails 方式是什么?
【发布时间】:2014-01-17 01:33:06
【问题描述】:

我有一个带有一个文本区域的简单表单,它将文本区域中的字符串作为 JSON 提交给外部 Web 服务。这是提交表单之前的样子:

这是提交表单后的样子:

这是创建表单的 html.erb 代码:

<script type="text/javascript">
  function call_service() {
    var data_to_send = document.getElementById("data_to_send").value;

    $.ajax({
      url : "http://externalservice.com",
      data : data_to_send,
      type : "POST",
      dataType : "json",
      contentType: "application/json"
    }).done(function(data) {
      // populate the table
    }).error(function(data) {
      // handle error
    });
  }

  $(document).ready(function() {
    $("#table_div").hide();
  });
</script>

<!-- heading html redacted -->

<!-- <%= form_tag("http://externalservice.com", 
                      method: :post,
                      remote: true,
                      role: "form",
                      data: "json") do %> -->

<form role="form">
  <h4 class="form-heading">Enter Data:</h4>
    <%= text_area_tag("data_to_send", @data, 
                          rows: 5, 
                          class: "form-control",
                          style: "font-family: Monaco;") %>
    <p class="help-block">
      Here you can edit the JSON data or click "Generate" to just
      use the data that's already there.
    </p>
    <%= button_to_function("Generate Table!", "call_service(); this.blur()" ,class: "btn btn-primary") %>
<!-- <% end %> -->
</form>

<!-- table html redacted -->

注释掉的form_tag 是我在决定使用jQuery 和button_to_function 位之前尝试做的事情。

我的问题是我如何完成同样的事情——将 JSON 数据发送到外部服务的表单——rails 方式?无论是remote: true 表单还是其他形式?

【问题讨论】:

    标签: ruby-on-rails json forms jquery ruby-on-rails-4


    【解决方案1】:

    如果第 3 方 Web 服务符合 REST,您可能想试试 ActiveResource

    另请阅读this Q/A 以获得更多提示。

    【讨论】:

    • 网络服务不是一个成熟的资源。我真的只对它的返回时间足够长以在同一页面上的表格中显示它感兴趣。大多数情况下,我只是好奇是否有更多的 Rails 方式来完成我手工破解的 Ajax 调用所完成的工作。不过感谢有关 ActiveResource 的提示!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    相关资源
    最近更新 更多