Javascript 从JSON url更改HTML5文本获取错误
我在获取内容和使用Reddit的subreddit数据替换文本时遇到问题。我尝试将带有ID title的h1文本替换为JSON文件中的一个文本,但我得到: 未捕获的SyntaxError:var上的意外数字 这是我用来更改文本的javascript文件Javascript 从JSON url更改HTML5文本获取错误,javascript,jquery,json,ajax,html,Javascript,Jquery,Json,Ajax,Html,我在获取内容和使用Reddit的subreddit数据替换文本时遇到问题。我尝试将带有ID title的h1文本替换为JSON文件中的一个文本,但我得到: 未捕获的SyntaxError:var上的意外数字 这是我用来更改文本的javascript文件 <script> $.ajax({ url: 'https://www.reddit.com/r/showerthoughts/top.json', dataType: 'json',
<script>
$.ajax({
url: 'https://www.reddit.com/r/showerthoughts/top.json',
dataType: 'json',
success: function( data )
{
var thought = data.children.0.data.title ;
var author = data.children.'0'.data.author ;
$('#title').text( thought );
}
});
</script>
$.ajax({
网址:'https://www.reddit.com/r/showerthoughts/top.json',
数据类型:“json”,
成功:功能(数据)
{
var Think=data.children.0.data.title;
var author=data.children.0.data.author;
$('标题')。文本(思想);
}
});
这是具有标题的HTML文件
<body>
<h1 class="title" id="title">Hello ! It's me</h1>
<h5 class="author">- author</h5>
<video autoplay loop poster="forest.jpeg" id="bgvid" controls muted>
<source src="walk.mp4" type="video/mp4">
</video>
</body>
你好是我
-作者
您不能执行数据.children.0
,请使用数据.children[0]
。点之后的任何内容都必须是有效标识符,并且不能以数字开头
请参见要访问数组元素,必须使用括号表示法,如下所示:
var thought = data.children[0].data.title;
var author = data.children[0].data.author;
编辑,这应该有用。您将收到一个响应对象,而不是数据本身。可在响应中找到数据。数据:
<script>
$.ajax({
url: 'https://www.reddit.com/r/showerthoughts/top.json',
dataType: 'json',
success: function(response)
{
var thought = response.data.children[0].data.title ;
var author = response.data.children[0].data.author ;
$('#title').text(thought);
}
});
</script>
$.ajax({
网址:'https://www.reddit.com/r/showerthoughts/top.json',
数据类型:“json”,
成功:功能(响应)
{
var think=response.data.children[0].data.title;
var author=response.data.children[0].data.author;
$('标题')。文本(思想);
}
});
json['data']['children'][0]['data']['title']这是我在braincast json编辑器中得到的内容。如果您执行以下操作,您在控制台中会得到什么:console.log(data)代码>编辑:我发现了你的问题,请查看我编辑的帖子