Reputation: 390
I have an application that makes multiple jsonp requests, all with the same jsonpCallback, which I can't change.
I tried to reproduce the situation in the following code.
The output is somewhat random, but it hardly includes all possible values for contextvar.
It seems to me that jquery registers "myFunc" globally, and that with each new request from requestMaker this association is overwritten.
How not to overwrite the contexts, in this case, how to print all the values?
<script type="text/javascript">
var requestMaker = function(url, contextvar) {
$.ajax({
url: url,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: "myFunc"
}).done(function(data) {
console.log(contextvar);
});
};
requestMaker("https://www.w3schools.com/js/demo_jsonp.php", "request1");
requestMaker("https://www.w3schools.com/js/demo_jsonp.php", "request2");
requestMaker("https://www.w3schools.com/js/demo_jsonp.php", "request3");
requestMaker("https://www.w3schools.com/js/demo_jsonp.php", "request4")
</script>
Upvotes: 0
Views: 53
Reputation: 28196
Yes, it looks like the callback function "myFunc"
is occupying the global scope and can therefore not be run in parallel. The following snippet runs the four jsonp calls consecutively, one after the other. Not ideal, but at least you get your results. Some APIs offer a parameter callback
or jsonp
for specifying the name of the padding callback function. The API used here however does not offer such a parameter.
var requestMaker = async function(url, contextvar) {
return $.ajax({
url: url,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: "myFunc",
}).done(function(data) {
console.log(contextvar,data);
});
};
(async function(){
await requestMaker("https://www.w3schools.com/js/demo_jsonp.php", "request1");
await requestMaker("https://www.w3schools.com/js/demo_jsonp.php", "request2");
await requestMaker("https://www.w3schools.com/js/demo_jsonp.php", "request3");
requestMaker("https://www.w3schools.com/js/demo_jsonp.php", "request4");
})(); // execute the async IIFE
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
jsonp
is considered to be a "historical" protocol for AJAX requests, initially proposed in 2004, see here: https://en.m.wikipedia.org/wiki/JSONP. It has certain security issues and was made obsolete by CORS in 2014.
Upvotes: 1