转换成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)是不是存在?

0
0

庚子年快乐

2021-02-18

首先你请求的文件里的数据需要是json格式吧!


0
1
江南沐小沐
是json,直接拷贝老师的文件。我运行老师的代码也是一样报这个错,xhr.responseText打印出来不是text.json里的对象
2021-02-18
共1条回复

一天时间高效准备前端技术一面 匹配大厂面试要求

针对时下面试高频考点,帮助新人js面试快速通关

4641 学习 · 1667 问题

查看课程