加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

jsonp 学习实例

发布时间:2020-12-16 19:14:16 所属栏目:百科 来源:网络整理
导读:jsonp.html !DOCTYPE htmlhtml head meta charset="utf-8" titlejsonp 跨域/title script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"/script /head body script type="text/javascript" // jquery 跨域传值 $(function(){ $.aja

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";
?>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读