PDA

View Full Version : JSONP2



Mycoding
8 Aug 2011, 8:59 AM
When I develop simple Sencha Touch chat I mention that JSONP function
works wrong cause it send to server not unique callback function name.

Request URL is like this


http://node.tw1.ru/?login=dfgd&action=getMessage&sid=1312822485111_gzytl&msg=&callback=Ext.util.JSONP.callback

So I decided to use JSONP function of David Flanagan that callback will be unique.
Here is code


/*
JSONP function on base of David Flanagan
Example:
Ext.util.JSONP2.request({url:'http://node.tw1.ru',callback:function(result){console.log(result);}});
*/


Ext.util.JSONP2 = {
callbackKey: 'callback',
counter:0,
request:function(obj){
if(!obj.url){
console.error('Not defined url for JSONP');
return;
}
var url = obj.url;
if(!obj.callback){
console.error('Not defined callback function for JSONP');
return;
}

var cbnum = "cb" + Ext.util.JSONP2.counter++,
cbname = "Ext.util.JSONP2." + cbnum,
callbackKey = obj.callbackKey || Ext.util.JSONP2.callbackKey;

if (url.indexOf("?") === -1){
url += "?callback=" + cbname;
}
else{
url += "&callback=" + cbname;
}

if(obj.params){
url+='&'+Ext.urlEncode(obj.params);
}

var script = document.createElement("script");
Ext.util.JSONP2[cbnum] = function(response) {
try{
obj.callback(response);
}
finally {
delete Ext.util.JSONP2[cbnum];
script.parentNode.removeChild(script);
}
};
script.src = url;
document.body.appendChild(script);
}
};


Here is live sample
http://moc-081.ru/chat/right.html - David Flanagan JSONP
http://moc-081.ru/chat/error.html - Sencha Touch JSONP