簡體   English   中英

發出簡單的 Ajax 請求

[英]Making a simple Ajax request

我正在嘗試使用 Lampp 服務器從我的本地計算機進行 Ajax 調用,但它一直出現此錯誤。

CORS 策略已阻止從源“null”訪問“file:///opt/lampp/htdocs/AjaxProject/sample.txt”處的 XMLHttpRequest:Z80791、43AE7009、FACB8888鍍鉻擴展,https。 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>

檢查文件和文件夾權限。 此外,您有時需要在 htaccess 中的允許擴展行中添加“txt”擴展名,這些擴展名可以由 web 瀏覽器執行。

某些安裝可能在 htaccess 中有這個,您可能需要修改:

      IndexIgnore *.zip *.txt

此外,有時,如果關閉文件導航,它會禁用 file:/// 協議。 檢查:

        Options -Indexes 

此外,設置 header 可能會導致瀏覽器更好地處理請求,因此,在 xhr.open() 行之后:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM