简体   繁体   English

发出简单的 Ajax 请求

[英]Making a simple Ajax request

Am trying to do an Ajax call from my local computer using Lampp server, and it keeps giving this error.我正在尝试使用 Lampp 服务器从我的本地计算机进行 Ajax 调用,但它一直出现此错误。

Access to XMLHttpRequest at 'file:///opt/lampp/htdocs/AjaxProject/sample.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. CORS 策略已阻止从源“null”访问“file:///opt/lampp/htdocs/AjaxProject/sample.txt”处的 XMLHttpRequest:Z80791、43AE7009、FACB8888镀铬扩展,https。 loadText @ trying.html:27 loadText@trying.html:27

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajak tutorials</title>

</head>
<body>
    <button id="button">Change text</button>
    <p id="text">Let Ajax change this </p>
    <script>
    document.getElementById('button').addEventListener('click',loadText);
    function loadText()
    {
        var xhr=new XMLHttpRequest();
        xhr.open('GET','sample.txt',true);
        xhr.onload=function(){
            if(this.status==200){
                document.getElementById('text').innerHTML=this.responseText;
            }else if(this.status==404){
                document.getElementById('text').innerHTML="Not found";
            }

        }

        xhr.send();
    }
    </script>
</body>
</html>

check file and folder permissions.检查文件和文件夹权限。 Also, you sometimes need to add the "txt" extension in htaccess on the line of permitted extensions that can be executed by the web browser.此外,您有时需要在 htaccess 中的允许扩展行中添加“txt”扩展名,这些扩展名可以由 web 浏览器执行。

some installations might have this in htaccess, that you might have to modify:某些安装可能在 htaccess 中有这个,您可能需要修改:

      IndexIgnore *.zip *.txt

Also, sometimes, if the file navigation is turned off, it would disable the file:/// protocal.此外,有时,如果关闭文件导航,它会禁用 file:/// 协议。 check for:检查:

        Options -Indexes 

Also, setting a header might cause the browser to handle the request better, so, right after the xhr.open() line:此外,设置 header 可能会导致浏览器更好地处理请求,因此,在 xhr.open() 行之后:

                xhr.setRequestHeader("Content-type", "text/plain");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM