4ndy 4ndy - 1 year ago 128
Ajax Question

Ajax Get is logged in console but won't print to page

Can someone point out the obvious as to why this response isn't printing to the page?

$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
contentType: 'application/json; charset=utf-8',
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});

$.get(
'https://data.nba.com/data/v2015/json/mobile_teams/nba/2017/scores/gamedetail/0011700003_gamedetail.json',
function (data) {
console.log("THE RESPONSE ", data);
setTimeout(function(){
$("#viewer").html(data);
}, 4000);


});


HTML

<div id="viewer"></div>


https://jsfiddle.net/nolaandy/df0jsdL0/1/

JSFiddle here shows that a JSON object is logged in the console.
I want to access the data in the response. I thought I'd start with just printing out the whole response to the "viewer" div but nothing appears there.

Answer Source

The reason nothing is rendered is because $.html() accepts a string to render as HTML, and you are providing an object.

If you want your object to be printed as a string, you can refactor to:

$("#viewer").html(JSON.stringify(data));

I think this will be really noisy, especially if the object is large. For debugging purposes, I think you are better off using the console.

Fiddle: https://jsfiddle.net/0x3j7fk1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download