About Loading the json File by $.ajax

Asked 2 years ago, Updated 2 years ago, 84 views

I tried to use $.ajax to read the local json file in Javascript, and when I ran the following code, it returned as a failure.

If you are familiar with it, please tell me the cause.(By the way, the json file is in the same hierarchy as this source file, so I think that's okay.Also, I did not get any errors when I did the parsing of the json file on the website.)

window.onload=function(){
    $.ajax({
        type: "get",
        url: "template.json",
        dataType: "json",
        success: function(data) { alert("success";},
        error: function() { alert("failure");}
    });
};

javascript json

2022-09-30 21:39

1 Answers

*Answer based on the assumption that the questioner is using a browser such as Google Chrome or Opera.

In browsers such as Google Chrome and Opera, Ajax requests to local files are blocked by default.

Issue 37586-chromium-An open-source project to help move the web forward.-Monorail

Issue 47416-chromium-An open-source project to help move the web forward.-Monorail

Firefox, on the other hand, allows to read files only in certain situations.

[1]

Starting with Gecko 1.9, only certain files are allowed to be read.Specifically, it can only be read if the parent directory of the source file is the same as the ancestor directory of the file to be read.However, the directory cannot be read this way.

Therefore, instead of Google Chrome or Opera, Firefox solves the questioner's problem.

Also, if you need to use Google Chrome, Opera, you can set the boot option (--allow-file-access-from-files) [2].[2]

In addition to the above, there are many other solutions.
Details about them are provided on the following web page, so you should read them once.


2022-09-30 21:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.