I plan on using JSONP to call an external 开发者_StackOverflow社区web service to get around the fact that I don't want to create a global function that could potentially conflict with the calling page. I thought that creating a random function name and passing it up would work. Something like this:
<script src="www.foo.com/b?cb=d357534">
where cb
is the callback function name, the server would return
d357534({my json data});
What I want to know is how to create the random function name, I'm sure I could use eval
but is this the best way to go about it?
Essentially, what I am trying to do is this:
var d + Math.floor(Math.random()*1000001) = function(){...
This should do what you want. You need to save the function name somewhere so that you can pass it to the server, but you can do that inside of a local scope to avoid polluting your global namespace.
var functionName = 'd' + Math.floor(Math.random()*1000001);
window[functionName] = function() { ... }
To make a randomly-named global variable you could do this:
window['randomvar' + Math.floor(Math.random()*1000001)] = function() { ... };
now of course you've got the problem of remembering the random name somewhere. You could make up a random name for that variable too. Then you'd have to remember the name of that variable, so that you could look at its value and then know how to find your function. After a while, things are going to start getting weird.
Why don't just use a counter and increment it each time you need a new function:
var name = "callback" + window.COUNTER++;
window[name] = function() { ... };
If you want to avoid littering the global namespace with too many references you could (and should) attach the counter and callbacks to a single global object:
var JSONP = window.JSONP;
var name = "callback" + JSONP.COUNTER++;
JSONP[name] = function() { ... };
In this case you could call the method like this:
JSONP.callback_12(json);
Of coarse you have to initialize the JSONP
object and the COUNTER
variable first.
精彩评论