sukkis sukkis - 2 months ago 10
JSON Question

How to print JSON objects correctly after successful JSONP request with Javascript

How to correctly parse/print JSON "scores" objects into demo div (I need just away, home and score data of each)?

My JSON query look like this (code below is also working)

{ "query": { "count": 18, "created": "2016-09-07T06:10:58Z", "lang": "fi", "results": { "json": [ { "scores": { "away": "ESBJERG ENERGY", "home": "EV ZUG", "match_type": "fin", "status": "fin", "matchId": "1311357", "score": "3-2", "image": "EUROPE (IIHF)" } }, { "scores": { "away": "HC DAVOS", "home": "ROUEN", "match_type": "fin", "status": "fin", "matchId": "1311356", "score": "2-3", "image": "EUROPE (IIHF)"}}]}}}




<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>

<body>
<div id="results"></div>

<div id="resultsshouldbelikethis">
EV ZUG - ESBJERG ENERGY (3-2)<br>
ROUEN - HC DAVOS (2-3)<br>
...and so on
</div>

<script>
jQuery.support.cors = true;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20scores%20from%20json%20where%20url%3D%22http%3a%2f%2fmobile.xscores.com%2fm_livescore%3fsport%3d4%26match_type%3dlive%26match_date%3d2016-09-06%26startPos%3d0%26endPos%3d5000%22%20limit%2050&format=json",
type: "GET",
timeout: 3000,
dataType: "jsonp",
success: function(parsa) {
document.getElementById("results").innerHTML =
parsa.query.scores;
console.log(parsa);
},
});
</script>





Console log works well but how to print results nicely into a div? "parsa.query.scores;" just results undefined.

Answer

You need to loop each data one-by-one and add them into div.

Try this:

    jQuery.support.cors = true;
    $.ajax({
        url: "http://query.yahooapis.com/v1/public/yql?q=select%20scores%20from%20json%20where%20url%3D%22http%3a%2f%2fmobile.xscores.com%2fm_livescore%3fsport%3d4%26match_type%3dlive%26match_date%3d2016-09-06%26startPos%3d0%26endPos%3d5000%22%20limit%2050&format=json"
        , type: "GET"
        , timeout: 3000
        , dataType: "jsonp"
        , success: function (parsa) {
            var strHtml = '';

            $.each(parsa.query.results.json, function (key, value) {
                strHtml += value.scores.home + ' - ' + value.scores.away;
                strHtml += '(' + value.scores.score + ')<br />';
            });

            document.getElementById("results").innerHTML = strHtml;
        }
    });
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>

<body>
  <div id="results"></div>
</body>