Django视图与跨域Ajax

时间:2013-12-03 14:41:34

标签: ajax django

我有一个Django视图,我希望与Ajax调用集成。呼叫正在跨域发生。我有这个代码自己运行并使请求跨域。

def myview(_request):  
    response = HttpResponse(json.dumps({"key": "value", "key2": "value"}))  
    response["Access-Control-Allow-Origin"] = "*"  
    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"  
    response["Access-Control-Max-Age"] = "1000"  
    response["Access-Control-Allow-Headers"] = "*"  
    return response  

我想知道如何将其整合到我现有的视图中。您将在下面的代码中看到我尝试过的内容:

def american_time(request):
    #Calling the HTML Source from the URL
    sock = urllib.urlopen("http://apps.cbp.gov/bwt/index.asp")
    htmlSource = sock.read()
    sock.close()
    #create a soup object
    soup = BeautifulSoup(htmlSource)
    #find the tags we need and their content
    bridge = soup.findAll('td', limit=215)[194]
    tunnel = soup.findAll('td', limit=250)[208]
    #new variables to be passed
    contents_of_tunnel = tunnel.getText(', ')
    contents_of_bridge = bridge.getText(', ')
    #check to see if there is a delay for the bridge
    if 'no delay' in contents_of_bridge:
        time_to_cross_the_bridge = 0
    else:
        inside_of_bridge = re.split(r', ', contents_of_bridge)
        number_inside_of_bridge = inside_of_bridge[1]
        list_for_time_to_cross_the_bridge = re.findall(r"\d+", number_inside_of_bridge)
        time_to_cross_the_bridge = list_for_time_to_cross_the_bridge[0]
    if 'no delay' in contents_of_tunnel:
        time_to_cross_the_tunnel = 0
    else:
        inside_of_tunnel = re.split(r', ', contents_of_tunnel)
        number_inside_of_tunnel = inside_of_tunnel[1]
        list_for_time_to_cross_the_tunnel = re.findall(r"\d+", number_inside_of_tunnel)
        time_to_cross_the_tunnel = list_for_time_to_cross_the_tunnel[0]
    response = HttpResponse(json.dumps({"bridge_time": time_to_cross_the_bridge,      "tunnel_time": time_to_cross_the_tunnel}))
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "*"
    #finally, return as Ajax
    return HttpResponse(response)

AJAX:

$.get( "http://localhost:8000/us", function(json){
$('#timeone').html(json.bridge_time + "min delay");
$('#timetwo').html(json.tunnel_time + "min delay");
})
.fail(function(){
    alert('We can\'t get data right now! Please try again later.');
})
.done(function(){
    alert('Success!');
});

但是,我仍然在控制台中收到消息XMLHttpRequest cannot load http://localhost:8000/us. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.。如何将此标题集成到我的视图中?

1 个答案:

答案 0 :(得分:2)

尝试添加此middleware

如何添加请参阅文档https://docs.djangoproject.com/en/dev/topics/http/middleware/