Ok, So I am trying to fetch data via jsonp using pure js (no jquery/ajax).I got to admit its been awhile since i'ave gone the pure js route so I am in need of a bit of help. This is my code so far:
<div id = 'inforoll'></div>
<script type="text/javascript">
function blah(data){
var copy = '';
var len = data.length;
for(var i=0;i<len;i++){
nLine = data[i];
copy += '<li id="' + nLine.render_client + '">' + nLine['copy'] + '</li>'
}
document.getElementById('inforoll').innerHTML = copy;
}
</script>
<script type="text/javascript" src="http://example.com/example.js"></script>
Example of the jsonp data trying to fetch:
blah.render_client({
"color": "blue",
"name": "bob"
}
Error being thrown:
Uncaught TypeError:Object function Blah(data){
var copy='',
var len = data.length;
for(var i=0;i<len;i++){
nLine = data[i];
copy += '<li id="' + nLine.render_client + '">' + nLine['copy'] + '</li>'
}
document.getElementById('inforoll').innerHTML = copy;
}has no method 'render-client'
Ok I got it, I need to create a method:
function blah(data){
this.render_client = This is where my brain stops working and I can't think of what to do next.
var copy = '';
var len = data.length;
for(var i=0;i<len;i++){
nLine = data[i];
copy += '<li id="' + nLine.render_client + '">' + nLine['copy'] + '</li>'
}
document.getElementById('inforoll').innerHTML = copy;
}
I just need some logical enlightenment, so I am all ears.Thanks All!
In JSONP a script tag is loaded which returns a function call with a JSON object as an argument. The expectation is that the function is already defined on the page. The reason is to get around the Same Origin Policy which normally prevents access to data from other domains using AJAX, but does allow you include script tags from other domains.
Okay, enough exposition, based on your example of the JSONP data you will need to define the object blah
that has a method render_client
. A very basic example of that would be:
<script type="text/javascript">
var blah = {
render_client: function(data) {
// data is the JSON object itself
var copy = '';
for(var prop in data){
copy += '<li id="' + prop + '">' + data[prop] + '</li>'
}
document.getElementById('inforoll').innerHTML = copy;
}
};
</script>
Note, in the example code I changed your for
, to a for..in
because you're iterating over an object. For the sake of simplicity I excluded the hasOwnProperty
check which is done to exclude inherited properties that you don't care about.