XMLHttpRequest无法加载http://example.com/myapp/jsonurl/.否'访问

XMLHttpRequest cannot load http://example.com/myapp/jsonurl/. No 'Access-Control-Allow-Origin' header is present on the requested resource

本文关键字:jsonurl 访问 myapp example 加载 http XMLHttpRequest com      更新时间:2023-09-26

$.ajax()从django项目的html页面请求,它可以使用firefox,但不能使用chrome。我尝试了很多谷歌的东西,但没有得到任何结果,我浪费了2天的plz帮助铬控制台错误:

XMLHttpRequest无法加载http://example.com/myapp/jsonurl/.请求的资源上不存在'Access-Control-Allow-Origin'标头。原点'http://www.example.com因此不允许访问。

我的代码:

ajax code:
 $.ajax({
    url: "http://example.com/myapp/jsonurl/",
    dataType:"json",
    type:"GET",
    success: function(data){
      alert(data);
    },
    error: function(xhRequest, ErrorText, thrownError){
      alert(xhRequest+ ErrorText+thrownError);
    }
  });

网址:

url(r'^jsonurl/', planViews.jsonurl,name='jsonurl'),

视图:

def jsonurltest(request):
    context = RequestContext(request)
    return HttpResponse(json.dumps("{'jsondata':'ajax test'}"), content_type="application/json")

两种解决方案:

请确保使用相同的名称(例如,两者均为www.example.com)

或者,如果必须保留两个不同的名称,请确保为AJAX调用提供服务的服务器添加一个标头:访问控制允许来源:http://www.example.com>

有关的更多信息,请访问:http://jquery-howto.blogspot.com/2013/09/jquery-cross-domain-ajax-request.html

最终我得到了解决方案在我的项目中有两个问题

1:安装https://github.com/ottoyiu/django-cors-headers

2:当用chrom所有浏览器正确删除此工作时,我在视图中使用了"@login_requested"