【问题标题】:Django view with cross-domain Ajax带有跨域 Ajax 的 Django 视图
【发布时间】:2013-12-03 14:41:34
【问题描述】:

我有一个想要与 Ajax 调用集成的 Django 视图。呼叫发生在跨域。我有这个代码自己运行并提出跨域请求。

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.。如何将此标头集成到我的视图中?

【问题讨论】:

标签: ajax django


【解决方案1】:

【讨论】:

  • 它不适合我。尝试了每个步骤和所有故障排除。有什么具体的看点吗?
猜你喜欢
  • 2010-10-08
  • 2013-02-03
  • 1970-01-01
  • 2012-05-23
  • 2013-11-09
  • 2012-12-06
  • 1970-01-01
  • 2017-11-16
  • 2016-11-06
相关资源
最近更新 更多