簡體   English   中英

我如何將數據發布到另一個網站並獲得 controller 動作響應來自網站的 http 響應

[英]How can i Post data to another website and get controller action respond to http response from the website

我是 ruby 的新手。 我想將包含 API 密鑰和其他一些字段數據的表單數據發布到另一個網站,該網站將驗證 http 響應 200 或 400 並將其發送到我的網站。 If I am able to connect to the api and get a 200 response, I want my controller to be able to create an object and show a corresponding message for same and if it fails, only show a message of failure to get response from the api .

我需要有關如何為此使用 controller 操作的幫助

這是我嘗試使用的代碼

<form action="/master/master" method="POST" >
  <script
    src="https://js.example.co/v7/inline.js" 
    data-key= <%= ENV["EXAMPLE_PUBLIC_KEY"] %>
     data-email= <%= current_user.email %> 
     data-ref= <% SecureRandom.random_number %> 
  >
   </script> 
 </form>

不確定為什么要在前端執行此操作,因為您還沒有解釋為什么要執行此操作的整個工作流程。 但是,如果您有充分的理由需要這樣做,例如在提交之前從用戶那里獲取其他表單數據,那么也許可以,這應該可行。 這種方法將進行 ajax 調用,然后您需要將數據 append 到您的表單中。 當您點擊提交時,表單數據將作為參數傳遞回您的 controller。 在此示例中,我將一些數據 object 轉換回字符串以粘貼到單個表單字段中。 這也假設您正在使用 jquery,它可能不會自動包含在您的 Rails 項目中。

<form action="/master/master" method="POST" >
  <%= label_tag(:ajax, "Ajax data") %>
  <%= text_field_tag(:ajax, '', {id: 'ajax-data'}) %>
  <%= submit_tag("Submit") %>
  <script>
    var postUrl = 'https://httpbin.org/post' // url here is proof of concept. You will change this.
    var data = {
      key: '<%= ENV["EXAMPLE_PUBLIC_KEY"] %>',
      email: '<%= current_user.email %>',
      ref: '<%= SecureRandom.random_number %>'
    }
    // console.log(data) uncomment to make sure your data is formatted correctly
    var postResponse
    $.post( postUrl, data)
      .done(function(res) {
        console.log(res)
        // you will need to figure out what data attributes to pass to your form
        $('#ajax-data').val(JSON.stringify(res.form)) // form is just a working example here
      })
      .fail(function(error){
        alert(error)
      })
  </script>
 </form>

但是,如果您不需要用戶提供任何東西,那么純后端方法會更好。 如果是這種情況,請告訴我們,我將再次更新此答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM