JSONP, CodeIgniter, and Bookmarklets
I'm building a bookmarklet app with CodeIgniter and JavaScript/jQuery. Right now my CI app is just returning a JSON encoded array to the bookmarklet script, b开发者_如何学运维ut obviously the jQuery won't be able to use that because it's not JSONP/cross-domain policy issues.
How can I make my CodeIgniter function return back JSONP results? I don't have the best understanding of JSONP, so please excuse my ignorance.
JSONP, as far as I know, is just loading a script from URL instead of making an XHR. Rather than returning json/xml/plain-text, the URL will return javasript. The javascript returned will simply be a call to a global function with the JSON data passed. jQuery conveniently creates this global function before the JSONP request and sends it's identifier as "callback" within the JSONP request.
To put it simply, you must access $_GET['callback'] (must use $.get for cross-domain) it holds the name of the callback function. For example:
<?php echo $_GET['callback']."(".json_encode($arrayJSONData).")"; ?>
This will return javascript which calls the global javascript function with the json data passed to it.
Remember that sense this isn't XHR/Ajax, but rather dynamicly appending a new DOM script element, you can't POST your data, thus no $_POST. How would you send POST data when you create a script element in HTML? It's GET data that's only able to be passed: <script src='someurl.php?this=getdatastuff'></script>
.
I think that's how it all works. xb
精彩评论