$.getJSON 获取数据
1.php
<?
header('Content-type:text/json');
$a=$_GET['callback'];
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo $a."(".json_encode($arr).")";
//echo $a.'({"Name":"loogn","Age":23})';
发起ajax请求时候会根据callback=? 参数 生成一个对回调方法的引用的名字
http://www.baidu.com/1.php?callback=jQuery21405223532722170716_1536589543709&_=1536589543710
返回值
jQuery21405223532722170716_1536589543709({"a":1,"b":2,"c":3,"d":4,"e":5})
AJAX POST
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>getJSON跨域</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<script>
$(function($) {
$.ajax({
url: "http://ln.chicagoenglish.com/ceshi/1.php",
type: "post",
data:{a:'a',b:'2'},
dataType: "json", //指定服务器返回的数据类型
success: function (data) {
console.log(data);
alert(data.a);
alert(data.b);
}
});
});
</script>
</body>
</html>
PHP
<?
header('Access-Control-Allow-Origin: *');//允许所有来源访问
header('Access-Control-Allow-Methods: POST');//响应类型
$arr = $_POST; //array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
AJAX GET
HTML
<script>
$(document).ready(function(){
$.ajax({
url: "http://www.xxx.cn/index.php",
type: "get",
dataType: "jsonp", //指定服务器返回的数据类型
success: function (data) {
console.log(data);
}
});
});
</script>
PHP