簡體   English   中英

如何從我的Django網站向其他服務器發出POST請求?

[英]How do I make a POST request to a different server from my Django-website?

我有一個在Django上運行的網站。 當用戶單擊提交按鈕時,我需要將數據發送到在不同域上運行的服務器,然后顯示返回給用戶的數據。 由於跨域問題,我無法使用Ajax請求。 很多消息來源建議我應該使用Javascript發送到我自己的服務器,然后發送到外部服務器,但我不知道如何實現它。

如果您提交表單最終需要訪問的URL,則可以在服務器端進行處理。 所以說你在表單中包含一個隱藏字段,如下所示:

<input type="hidden" name="form_urlfield" value="http://anotherwebsite.com/wheretheformneedstogo">

基本上你可以這樣做:

        $.ajax({
    type: "POST",
    url: 'http://somewhereonthesameserver.com/submit-form',
    data: $('#ajax-form').serialize(),
    success: function(data){...},
            });

然后,在與提交表單URL對應的視圖中:

import urllib2
data = urllib2.urlopen(request.POST['form_urlfield'], the_post_data)
//the_post_data is the data that you want to post to the other server..
// do something with the returned data
// return a JSON/Other response

另外,請確保在Django中啟用CSRF-Ajax功能。 https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/#csrf-ajax

以上所有內容都只是偽代碼(我剛剛在這里寫了..)但它應該讓你知道如何繼續。 希望這可以幫助 :)

您可以從django應用程序發出http請求。

  1. user從html表單向django提交數據
  2. 使用urllib發送數據並從其他域獲取響應
  3. 將適當的響應數據提交給用戶。

Ashray和dm03514提供的答案是正確的。 但我可能會建議使用Requests而不是urllib2來進行服務器端HTTP處理。

暫無
暫無

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

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