簡體   English   中英

如何在沒有Jquery的情況下使用JavaScript在本地加載json文件?

[英]How to load a json file with javascript locally without Jquery?

我正在創建一個使用javascript進行開發的網站,但我嘗試使用的所有方式都存在一個小問題,我的瀏覽器不想加載json文件。

我嘗試了很多在Internet上找到的代碼,但是沒有一個起作用(或者我不知道如何使它們起作用)。 最后,我喜歡這個很容易理解的樣式,但是您的樣式也不起作用,並且總是返回錯誤消息。


function loadJSON(path,success, error)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 1) {
                if (success)
                    success(JSON.parse(xhr.responseText));
            } else {
                if (error)
                    error(xhr);
            }
        }
    };
    xhr.open("GET", path , true);
    xhr.send();
}

function test()
{
    loadJSON('test.json', function(data) { console.log(data); }, function(xhr) { console.error(xhr); });
}

我運行測試功能,但每次控制台都會向我返回錯誤。 有人有解決我問題的想法嗎?

status是HTTP響應代碼。

200表示請求已成功。 該狀態極有可能永遠不會為1。

這是HTTP代碼列表

作為解決方案,我建議使用fetch API ,這是查詢文件的現代方法。

這是一些使用方法的例子


如果您真的想使用AJAX,請使用以下命令:

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (this.status >= 200 && this.status < 400) {
    // Success!
    var resp = this.response;
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

資料來源: 您可能不需要jQuery

暫無
暫無

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

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