Javascript XMLHttpRequest 无法加载 Origin null 不允许 Access-Control-Allow-Origin

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7092060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:48:57  来源:igfitidea点击:

XMLHttpRequest cannot load Origin null is not allowed by Access-Control-Allow-Origin

phpjavascript

提问by Thasni anes

I have a code.html file containing the following code.

我有一个包含以下代码的 code.html 文件。

 $.ajax({ 
                    type: "POST", 
                    datatype: "JSONP",
                    url: "path",
                    success: function(msg){
                    var e = document.createElement("div");
                    e.id = "ads";
                    document.body.appendChild(e);
                    $("#ads").html(msg);

                    }
           });

When I open the code.html file in the browser, it gives an error:

当我在浏览器中打开 code.html 文件时,它给出了一个错误:

**"XMLHttpRequest cannot load file://..... Origin null is not allowed by Access-Control-Allow-Origin."**

Please help me!! how to avoid this problem

请帮我!!如何避免这个问题

回答by Josep Valls

I will make two assumptions:

我会做两个假设:

  • You are probably using chrome
  • You are opening a file from the filesystem (i.e. double clicking)
  • 您可能正在使用 chrome
  • 您正在从文件系统打开一个文件(即双击)

Then, this question is a duplicate of XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

然后,这个问题是重复的XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

The browser is preventing cross site scripting. See: https://developer.mozilla.org/en-US/docs/HTTP_access_control

浏览器正在阻止跨站点脚本。请参阅:https: //developer.mozilla.org/en-US/docs/HTTP_access_control

回答by wukong

if you your dataType is jsonp(lowercased), the ajax type must be GETnot POST

如果您的 dataType 是jsonp(小写),则 ajax 类型必须GET不是POST

Update:

更新:

Use $.getJSON insteadof $.ajax should solve your problem

使用 $.getJSON 而不是 $.ajax 应该可以解决您的问题