js


Jul. 15, 2013

JSONP and JSON

Let’s see what’s differences between JSON and JSONP first; //JSON {"name":"stackoverflow","id":5} //JSONP func({"name":"stackoverflow","id":5}); JSONP is the result that you can load the json as a script file. And it is usually used to allow for cross-site AJAX with JSON data. function func(json){ alert(json.name); } var elm = document.createElement("script"); elm.setAttribute("type", "text/javascript"); elm.src = "http://example.com/jsonp"; document.body.appendChild(elm); Convert JSON to JSONP in PHP, JSONP will pass callback to script $json = json_encode($data); $jsonp_callback = isset($_GET['callback']) ? $_GET['callback'] : null; echo $jsonp_callback ? "$jsonp_callback($json)" : $json; Rerference: Stack Overflow