Javascript jquery getjson成功函数不工作
首先,我使用wampserver作为我的本地web服务器,我的本地环境的网站链接是Javascript jquery getjson成功函数不工作,javascript,jquery,json,Javascript,Jquery,Json,首先,我使用wampserver作为我的本地web服务器,我的本地环境的网站链接是http:\\localhost\dev\mywebsite,我在网站根目录(http:\\localhost\dev\mywebsite\country.JSON)中有一个本地JSON文件(country.JSON)然后我尝试加载它,并尝试使用 $.getJSON('http:\\localhost\dev\mywebsite\country.json',function(e){ console.log
http:\\localhost\dev\mywebsite
,我在网站根目录(http:\\localhost\dev\mywebsite\country.JSON
)中有一个本地JSON
文件(country.JSON
)然后我尝试加载它,并尝试使用
$.getJSON('http:\\localhost\dev\mywebsite\country.json',function(e){
console.log(e);
});
但工作方式不一样,我可以在开发者控制台(chrome)的网络选项卡上看到json文件在那里,但是
控制台日志(e)
没有触发。有什么想法吗?控制台上没有错误,因为
\
是JS字符串中的转义字符,所以您的路径不正确
'http:\\localhost\dev\mywebsite\country.json'
/* ends up looking like this `http:\localhostdevmywebsitecountry.json`*/
/* should be: */
'http://localhost/dev/mywebsite/country.json'
应该使用斜杠而不是反斜杠
$.getJSON('http://localhost/dev/mywebsite/country.json',function(e){
console.log(e);// Works OK
});
或者你可以使用fetch(像Promise一样)
或者可以使用fetch(与async/await一起使用)
是否可以通过URL访问该文件?我的意思是,直接在浏览器中写入URL
ttp:\\localhost\dev\mywebsite\country.json
路径不正确,JS中的\
是转义字符,请改用/
。实际上,您正在尝试从“http:\localhostdevmywebsitecountry.JSON”读取JSON。@MrMins是的,使用is直接在浏览器上浏览JSON文件working@Teemu那为什么我在开发者控制台(chrome)的网络标签上看到它被加载了,如果你说路径不正确的话?我不知道,也许只是在帖子中路径是错误的?
fetch('http://localhost/dev/mywebsite/country.json')
.then(e => e.json())
.then(e => console.log(e));
(async ()=> {
const res = await fetch('http://localhost/dev/mywebsite/country.json')
const json = res.json();
console.log('json', json)
})();