I'm trying out some jQuery / AJAX tutorials; specifically this one: https://www.youtube.com/watch?v=fEYx8dQr_cQ
He has is external API returning the following JSON (and it works!):
[
{
name: 'john',
drink: 'coffee'
},
{
name: 'jack',
drink: 'latte'
}
]
But when I try that locally (running http-server) I keep getting errors saying:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [
{
name: 'john',
drink: 'coffee'
},
{
name: 'jack',
drink: 'latte'
}
]
But when I put everything in double quotes, I no longer get any errors (makes sense, since now it is valid JSON):
[
{
"name": "john",
"drink": "coffee"
},
{
"name": "jack",
"drink": "latte"
}
}
The next issue then was that my code doesn't get any of the data. I then learned that I had to add the option dataType = "JSON" for it to work, while the video did not have to do that.
Why is this the case?
var $content = $( '.content' );
$( function () {
$.ajax( {
type: 'GET',
url: './orders.api.js',
success: function( data ){
console.log(data);
$.each( data, function( index, order ) {
$content.append( '<li>' + order.name + ' likes ' + order.drink + '</li>' );
});
}
});
});
<div class="content">
<ul></ul>
</div>
I'm getting confused as to why everything works in the video, but when I copy it exactly it does not work for me.
How did he have a API returning JSON with single quotes? How did he not have to use dataType='JSON'?