从JSON url更改HTML5文本时收到错误

时间:2016-03-31 12:14:58

标签: javascript jquery json ajax html5

我在使用Reddit的subreddit淋浴思想获取数据时获取内容并替换文本时遇到问题。我要做的是将ID标题的h1文本替换为JSON文件中的一个,但我得到:

Uncaught SyntaxError:var think的意外数字。

这是我用于更改文字的javascript文件

<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>

这是具有标题的HTML文件。

 <body>
    <h1 class="title" id="title">Hello ! It's me</h1>
    <h5 class="author">- UnknownDeveloper</h5>
    <video autoplay loop poster="forest.jpeg" id="bgvid" controls muted>
        <source src="walk.mp4" type="video/mp4">
    </video>
    </body>

2 个答案:

答案 0 :(得分:0)

您不能data.children[0]使用<?php $ip='94.219.40.96'; print_r(geoCheckIP($ip)); //Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen ) //Get an array with geoip-infodata function geoCheckIP($ip) { //check, if the provided ip is valid if(!filter_var($ip, FILTER_VALIDATE_IP)) { throw new InvalidArgumentException("IP is not valid"); } //contact ip-server $response=@file_get_contents('http://www.netip.de/search?query='.$ip); if (empty($response)) { throw new InvalidArgumentException("Error contacting Geo-IP-Server"); } //Array containing all regex-patterns necessary to extract ip-geoinfo from page $patterns=array(); $patterns["domain"] = '#Domain: (.*?)&nbsp;#i'; $patterns["country"] = '#Country: (.*?)&nbsp;#i'; $patterns["state"] = '#State/Region: (.*?)<br#i'; $patterns["town"] = '#City: (.*?)<br#i'; //Array where results will be stored $ipInfo=array(); //check response from ipserver for above patterns foreach ($patterns as $key => $pattern) { //store the result in array $ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found'; } return $ipInfo; } ?> 。点之后的任何内容都必须是有效的标识符,并且它们不能以数字开头。

请参阅What characters are valid for JavaScript variable names?

答案 1 :(得分:0)

为了访问数组元素,你必须使用括号表示法:

var thought = data.children[0].data.title;
var author = data.children[0].data.author;
编辑,这应该工作。您将收到响应对象,而不是数据本身。数据可在response.data找到:

<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>