使用jQuery加载本地JSON文件遭遇跨域错误问题求助
Hey there! That error you're hitting is totally normal when you're trying to load local files directly in your browser—let's break down what's going on and how to fix it quickly.
Why This Happens
When you double-click your HTML file to open it, your browser uses the file:// protocol instead of http:// or https://. Browsers have strict security rules (called the same-origin policy) that block AJAX requests (like $.getJSON) from file:// URLs because they pose potential security risks. The error message is just the browser letting you know it won't allow this kind of request for non-web protocols.
Solutions to Try
1. Use a Local Development Server (Recommended)
This is the most reliable approach, since it mimics the environment your code will run in online. Here are a few easy ways to set one up:
- Python Built-in Server:
- If you have Python 3, open a terminal in your project folder and run:
python -m http.server 8000 - For Python 2, run:
python -m SimpleHTTPServer 8000
http://localhost:8000to load your HTML file. Now your$.getJSONcall will work because you're using thehttp://protocol. - If you have Python 3, open a terminal in your project folder and run:
- Node.js http-server:
First install it globally (if you have Node.js installed):
Then run it in your project folder:npm install -g http-server
Follow the terminal's instructions to access your files via the provided local URL.http-server
2. Modify Browser Security Settings (For Testing Only)
You can disable the browser's same-origin policy temporarily, but don't use this for regular browsing—it lowers your security. Here's how for Chrome:
- Windows: Right-click your Chrome shortcut, go to "Properties", and add this to the end of the "Target" field:
--disable-web-security --user-data-dir="C:/ChromeDevSession" - Mac: Open Terminal and run:
Use this Chrome window to load your HTML file, and the cross-origin error will be gone. Remember to close this window and revert the settings when you're done testing.open -n -a "Google Chrome" --args --disable-web-security --user-data-dir="/tmp/ChromeDevSession"
3. Embed JSON Directly in JavaScript (Quick Temporary Fix)
If you just need to test your code without setting up a server, copy the contents of phones.json into a JavaScript variable in your HTML file:
<html lang="en"> <head> <meta charset="utf-8"> <title>TEST</title> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> // Paste your phones.json content here const phoneData = { "phones": [ {"name": "Phone 1", "brand": "Brand A"}, {"name": "Phone 2", "brand": "Brand B"} // Add all your JSON content here ] }; // Now you can use the data directly instead of $.getJSON console.log('It Worked!', phoneData); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Avi

