1) 什么是JSONP? <script type="text/javascript" src="http://www./myService.aspx?jsonp=callbackFunction" />
2. 在客戶端寫callbackFunction函數(shù)的實(shí)現(xiàn) <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> 3. 頁(yè)面展示 <div id="divCustomers"></div>
4. 最終Page Code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www./1999/xhtml" > <head> <title>Top Customers with Callback</title> </head> <body> <div id="divCustomers"></div> <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> <script type="text/javascript" src="http://www./myService.aspx?jsonp=callbackFunction"></script> </body> </html> 3) JSONP在JQuery中如何體現(xiàn)的 1. $.getJSON <script>
$(document).ready(function(){ $.getJSON("http://api./services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data){ $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); }); }); </script> jsoncallback=?,,其中,?會(huì)自動(dòng)替換為function(data)函數(shù)。 2. $.ajax $.ajax({
dataType: 'jsonp', data: 'id=10', jsonp: 'jsonp_callback', url: 'http:///getdata', success: function () { // do stuff }, }); 4) 如何在服務(wù)器端實(shí)現(xiàn)對(duì)JSON支持? 注:Callback僅僅是JSONP的簡(jiǎn)單實(shí)現(xiàn),,可以根據(jù)具體需要實(shí)現(xiàn)更復(fù)雜的功能,,比如可以在客戶端動(dòng)態(tài)集成更多的變量數(shù)據(jù)來(lái)完成分頁(yè)功能,。 |
|