0

我有一个在 Django 上运行的网站。当用户单击提交按钮时,我需要将数据发送到运行在不同域上的服务器,然后显示返回给用户的数据。由于跨域问题,我无法使用 Ajax 请求。许多消息来源建议我应该使用 Javascript 发送到我自己的服务器,然后再发送到外部服务器,但我不知道我将如何实现它。

4

3 回答 3

2

如果提交表单最终需要去的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

以上所有只是伪代码(我只是在这里写出来的......)但它应该让你知道如何继续。希望这可以帮助 :)

于 2012-07-15T23:10:24.850 回答
0

您可以从 django 应用程序发出 http 请求。

  1. 用户从 html 表单向 django 提交数据
  2. 使用 urllib 发送数据并从其他域获取响应
  3. 向用户提交适当的响应数据。
于 2012-07-15T22:54:38.307 回答
0

Ashray 和 dm03514 提供的答案是正确的。但我可能会建议考虑使用Requests而不是 urllib2 进行服务器端 HTTP 处理。

于 2012-07-16T08:31:04.723 回答