YouTip LogoYouTip

Json Jsonp

In this section, we will introduce you to JSONP. Jsonp (JSON with Padding) is a "usage pattern" for JSON that allows a web page to retrieve data from a different domain (website), i.e., cross-domain data reading. Why do we need a special technique (JSONP) to access data from different domains (websites)? This is because of the Same-Origin Policy. The Same-Origin Policy is a famous security policy proposed by Netscape. Now, all browsers that support JavaScript use this policy. * * * ## JSONP Application ### 1. Server-Side JSONP Format Data If a client wants to access: ** Assume the client expects the returned data to be: ["customername1","customername2"]. The data actually returned to the client is displayed as: callbackFunction(["customername1","customername2"]). The server-side file `jsonp.php` code is: ## jsonp.php File Code ### 2. Client-Side Implementation of the callbackFunction Function function callbackFunction(result, methodName){var html = '
    '; for(var i = 0; i<result.length; i++){html += '
  • ' + result + '
  • '; }html += '
'; document.getElementById('divCustomers').innerHTML = html; } ### Page Display
### Complete Client-Side Page Code JSONP Example
function callbackFunction(result, methodName){var html = '
    '; for(var i = 0; i<result.length; i++){html += '
  • ' + result + '
  • '; }html += '
'; document.getElementById('divCustomers').innerHTML = html; } * * * ## jQuery Using JSONP The above code can be implemented using jQuery: JSONP Example
$.getJSON("", function(data){var html = '
    '; for(var i = 0; i<data.length; i++){html += '
  • ' + data + '
  • '; }html += '
'; $('#divCustomers').html(html); });
← Css3 GradientsJs Void β†’