I have this code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('http://example.com/api/get_cats', function(fbResults) {
document.write(fbResults.cats[0].title);
});
});
</script>
How can I change this code:
<script>
$(document).ready(function() {
$.getJSON('http://example.com/api/get_cats', function(fbResults) {
document.write(fbResults.cats[0].title);
});
});
</script>
for it to work as JSONP ... Is this totally different?
JSONP is not actually JSON with padding, it's Javascript code that's executed. JSON is not a real subset of Javascript and the way it is not is important to us: via UTFGrid, we are all UTF-8 masters. JSONP is not safe: it's Javascript that's executed. It's trivial to XSS with JSONP, because JSONP is XSS.
Yes, JSONP is obsolete now. There's absolutely no reason to offer a JSONP service anymore.
It's idea is to simply return a JavaScript file which calls the callback function with the JSON object as the first parameter of the JavaScript callback function. You can use the built-in json_encode() function to create JSON strings (which $data in our example above contains) from arrays and objects in PHP.
Method to use JSONP:In HTML code, include the script tag. The source of this script tag will be the URL from where the data to be retrieve. The web services allow to specify a callback function. In the URL include the callback parameter in the end.
Actually, you just have to add ?callback=?
, jQuery does the rest.
$(document).ready(function() {
$.getJSON('http://example.com/api/get_cats?callback=?', function(fbResults) {
document.write(fbResults.cats[0].title);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With