如何使用js(jQuery)加载json?
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                在JavaScript中,您可以使用fetch API或XMLHttpRequest来加载JSON文件。在jQuery中,您可以使用$.getJSON方法。以下是使用这两种方法的示例代码:
使用原生JavaScript的fetch API加载JSON:
fetch('example.json')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // 处理JSON数据
  })
  .catch(error => console.error('Error fetching JSON:', error));使用原生JavaScript的XMLHttpRequest加载JSON:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.json', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var json = JSON.parse(xhr.responseText);
    console.log(json);
    // 处理JSON数据
  }
};
xhr.send();使用jQuery的$.getJSON方法加载JSON:
$.getJSON('example.json', function(data) {
  console.log(data);
  // 处理JSON数据
})
.fail(function(jqXHR, textStatus, errorThrown) {
  console.error('Error fetching JSON:', textStatus, errorThrown);
});请确保您的服务器配置允许跨域请求(CORS),除非JSON文件与您的网站在同一个域上。
评论已关闭