jsonp.html
<!DOCTYPE html> <html> <head> <Meta charset="utf-8"> <title>jsonp 跨域</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <script type="text/javascript"> // jquery 跨域传值 $(function(){ $.ajax({ url:"http://dev.fangfull.com/html/ff/test.PHP",dataType: "jsonp",jsonp: "cb",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback) jsonpCallback:"test",//需要的回调函数 success: function(data){ //alert(data.name); var $ul = $("<ul></ul>"); console.log(data); var data = eval(data); console.log(data); for( var i = 0; i<data.length; i++){ $("<li/>").text(data[i].name + " " +data[i].sex).appendTo($ul); } // $.each(data,function(i,v){ // $("<li/>").text(v.name + " " + v.sex).appendTo($ul) // }); //$re = '[{"name":"wxf","sex":"female"},{"name":"xjj","sex":"male"}]'; 输出json格式字符串,对象 二维数组 // $("<li/>").text("姓名:" + data.name + " 性别:" + data.sex).appendTo($ul); //PHP json_encode 一维数组 $("#remote").append($ul); },error: function(){ alert('fail'); } }) }) // js跨域传值 //回调函数 function test(str){ alert(str[0].name); } setTimeout(function(){ var url = "http://dev.fangfull.com/html/ff/test.PHP?cb=test"; var script = document.createElement('script'); script.setAttribute('src',url); document.getElementsByTagName("body")[0].appendChild(script); },100) </script> <div id="remote"></div> </body> </html>
test.PHP
<?PHP $str = $_GET['cb']; // $arr = array( // 'name' =>'wxf',// 'sex' => 'female' // ); // $a = array('name' => 'wxf','sex' => 'female' ); // $b = array('name' => 'xdf','sex' => 'female' ); // $c = array('name' => 'sl','sex' => 'male'); // $arr = array($a,$b,$c); $arr=array( "0"=>array( "name"=>"wxf","sex"=>"female" ),"1"=>array( "name"=>"xdf","2"=>array( "name"=>"sl","sex"=>"male" ) ); $re = json_encode($arr); // $re = '[{"name":"wxf","sex":"male"}]'; $re = $str."(".$re.")"; echo "$re"; ?>