首页 > 技术文章 > jsonp 使用示例

junxizai 2014-08-07 15:45 原文

客户端:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script src="http://img1.tuniucdn.com/j/201406191714/3rd/jquery-1.7.2.min.js"></script>
<!-- <script src="../js/require.js" data-main="../js/main"></script> -->
<script type="text/javascript">

自定义回调函数

$.ajax({
url: "http://localhost/html/index.php",
type: "GET",
dataType: "jsonp",
jsonp: "js_callback",
jsonpCallback: "cjCallback",
success: function(data){
    console.log(data);
  }
})

 

默认回调函数

$.ajax({
url: "http://localhost/html/index.php",
type: "GET",
dataType: "jsonp",
jsonp: "callback",
success: function(data){
    console.log(data);
  }
})

 

 

 

 


</script>


</body>
</html>

 

服务器端:

<?php

header('Content-Type:text/json;charset=utf-8');
$str = array
(
'Name'=>'xiaolou',
'Age'=>20
);

$jsonencode = json_encode($str);
echo $_GET["jsonp_callback"]."(".$jsonencode.")";

?>

推荐阅读