ajax jsonP 解决跨域问题
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> function fn1(data){ var oUl1 = document.getElementById('ul1'); var html = ''; for (var i=0; i<data.length; i++) { html += '<li>'+data[i]+'</li>'; } oUl1.innerHTML = html; } function fn2(data){ var oUl2 = document.getElementById('ul2'); var html = ''; for (var i=0; i<data.length; i++) { html += '<li>'+data[i]+'</li>'; } oUl2.innerHTML = html; } window.onload = function(){ var oBut1 = document.getElementById('btn1'); var oBut2 = document.getElementById('btn2'); oBut1.onclick = function(){ var oScript = document.createElement('script'); oScript.src = 'jsonP.php?callback=fn1'; document.body.appendChild(oScript); }; oBut2.onclick = function(){ var oScript = document.createElement('script'); oScript.src = 'jsonP.php?callback=fn2'; document.body.appendChild(oScript); }; }; </script> </head> <body> <input type="button" id="btn1" value="加载数字"/> <ul id="ul1"></ul> <input type="button" id="btn2" value="加载字母"/> <ul id="ul2"></ul> </body> </html>
<?php //$t = isset($_GET['t']) ? $_GET['t']:'num'; $t = isset($_GET['t']) ? $_GET['t'] : 'num'; $callback = isset($_GET['callback']) ? $_GET['callback'] : 'fn1'; $arr1 = array('111111','22222222','33333333','4444444','555555555555555555555'); $arr2 = array('aaaaaaaaaaaa','bbbbbbbb','cccccccccccc','ddddddddd','eeeeeeeeeeee'); if ($callback == 'fn1') { $data = json_encode($arr1); } else { $data = json_encode($arr2); } echo $callback.'('.$data.');';