What is JSONP?
JSONP is an unofficial protocol that allows the server to integrate Script tags to return to the client and implement cross-origin access through javascript callback (this is only a simple implementation form of JSONP ).
How to Use JSONP
Call the URL Service provided by JSONP on the client to obtain JSONP format data.
For example, if a customer wants to access a http://www.myserver.com/myService.aspx? Jsonp = callbackFunction. If the customer expects to return JSON data: ["mermername1", "customername2"], the Script Tags: callbackFunction (["customername1 ", "mermername2"]), the possible call method:
<script type="text/javascript" src="http://www.myserver.com/myService.aspx?jsonp=callbackFunction" />
Implementation of callbackFunction writing on the client
<script type="text/javascript">function onCustomerLoaded(result, methodName){var html = '<ul>';for(var i = 0; i < result.length; i++){html += '<li>' + result[i] + '</li>';}html += '</ul>';document.getElementById('divCustomers').innerHTML = html;}</script>
Page display:
<div id="divCustomers"></div>
Final Page Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">How does JSONP express in JQuery?
$. GetJSON:
<script>$(document).ready(function(){$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",function(data){$.each(data.items, function(i,item){$("
Jsoncallback = ?, Where? It is automatically replaced with the function (data) function.
$. Ajax:
$.ajax({ dataType: 'jsonp', data: 'id=10', jsonp: 'jsonp_callback', url: 'http://myotherserver.com/getdata', success: function () { // do stuff },});
How to Implement JSON support on the server side
In this case, you only need to convert the JSON data of the Service to the desired script tags format. The format can be defined by yourself. After all, this is an unofficial protocol.
Note: Callback is only a simple implementation of JSONP. You can implement more complex functions as needed. For example, you can dynamically integrate more variable data on the client to complete the paging function.