转换成json对象报错
来源:12-4 实现跨域的常见方式 - jsonp 和 CORS
			江南沐小沐
2021-02-18

js代码
const xhr = new XMLHttpRequest()
xhr.open('GET', '/data/test.json', true)
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(xhr.responseText)
            alert(xhr.responseText)
        } else if (xhr.status === 404) {
            console.log('404 not found')
        }
    }
}
xhr.send(null)
xhr.responseText打印出来是这样子
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<meta name="viewport" content="width=device-width, initial-scale=1">
	</head>
	<body>
		<p style="width: 100%;text-align: center;font-size: 140px;height: 40px;">404</p>
		<p style="width: 100%;text-align: center;font-size: 40px;">Page Not Found</p>
		<!-- p style="width: 100%;text-align: center;font-size: 18px;">访问<a href="http://www.dcloud.io" target="_blank">DCloud官网</a>或<a href="http://ask.dcloud.net.cn" target="_blank">社区</a></p> -->
		
	<script>document.write('<script src="//' + (location.host || 'localhost').split(':')[0] + ':35929/livereload.js?snipver=1"></' + 'script>')</script><script>document.addEventListener('LiveReloadDisconnect', function() { setTimeout(function() { window.location.reload(); }, 500); })</script></body>
</html>
写回答
	2回答
- 
				
						双越
2021-02-18
xhr.responseText 打印的结果,是一个 404 页面的 html ,不是 json 格式,所以报错。
所以,你看下 url (即 /data/test.json)是不是存在?
00 - 
				
						庚子年快乐
2021-02-18
首先你请求的文件里的数据需要是json格式吧!
012021-02-18