来自Javascript / Django的POST RESTful api调用

时间:2013-08-07 20:05:39

标签: javascript jquery python django api

我正在尝试通过Javascript上的按钮进行POST RESTful api调用。 api调用是跨域的,因此这是一个挑战。我该如何打电话?

在ajax中我的调用如下:[我现在知道你不能从ajax进行跨域调用]:

                $.ajax({
                    type: 'POST',
                    dataType: 'application/json',
                    accept: 'application/json',
                    async: false,
                    username: 'user',
                    password: 'name',
                    url: 'http://exterenal.website',
                    data: {
                        "name": "Marcus0.7",
                        "start": 500000,
                        "end": 1361640526000
                    },
                    success: function(){alert('DONE!');},
                    error:function(){alert('ERROR!')},
            });
在python中

调用看起来像:

r = requests.post('http://externenal.website' ,headers={'content-type': 'application/json'}, auth=auth, data=json.dumps(data))

由于

1 个答案:

答案 0 :(得分:2)

你需要使用JSONP而不是json。问题是xmlhttprequest有一个策略,声明您不能在当前站点域之外发出请求。 JSONP是一个解决这个问题的技巧。

请注意您违反了安全政策。

Here's a So post that explains how to do this using JQuery.