Ajax异步请求,获取本地json数据
    		       		warning:
    		            这篇文章距离上次修改已过440天,其中的内容可能已经有所变动。
    		        
        		                
                要使用Ajax异步请求获取本地JSON数据,你可以使用JavaScript的XMLHttpRequest对象或者现代的fetchAPI。以下是使用这两种方法的示例代码。
使用XMLHttpRequest的示例:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var json = JSON.parse(xhr.responseText);
    console.log(json); // 处理获取到的JSON数据
  }
};
xhr.send();使用fetch API的示例:
fetch('data.json')
  .then(response => response.json())
  .then(json => {
    console.log(json); // 处理获取到的JSON数据
  })
  .catch(error => console.error('Error fetching data:', error));在这两种方法中,你需要确保data.json文件位于可以访问的服务器上的正确路径上,或者在浏览器的同源策略允许的范围内。如果是本地测试,你可能需要运行一个本地服务器,因为浏览器的同源策略会阻止从本地文件系统直接请求资源。
评论已关闭