jquery读取jsonp数据代码
jquery读取jsonp数据,下面以PHP作为jsonp的返回服务端页面,用jquery的$.getJSON获取jsonp数据
示例PHP代码:
$callback = $_GET["callback"];
$a = array(
'name'=>'张三',
'sex'=>'男',
'age'=>24,
'name'=>'李四',
'sex'=>'男',
'age'=>26,
);
$result = json_encode($a);
echo "$callback($result)";
exit;
=======================================================
jquery代码:
$.getJSON("http://www.35ui.cn/jsonp.php?callback=?",function(json){
console.log(json.name);
});
测试发现getJSON 的callback 只能是 =? 不能是其他名字,如果是其他名字就提示跨域了,完整的ajax写法是可以的,如下:
$.ajax({
type: "GET",
url:"../json/test.json",
dataType: "jsonp",
jsonp: "callback", //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
jsonpCallback:"test", //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
success: function(json){
console.log(json.name);
},
error: function(){
console.log("fail");
}
});
});
//用$.ajax的方式是可以执行test(arr)的
function test(arr){
console.log(arr.name)
}
//json模拟数据
在json测试目录下新建test.json 测试数据
test({
"totalNum": 162,
"personList": [
{
"createTime": "2015-12-21 16:28:57",
"giftLevel": 6,
"giftName": "10元代金券",
"id": "",
"mobile": "13800000011",
"number": "",
"userId": "100152996585"
},{
"createTime": "2015-12-21 16:28:57",
"giftLevel": 6,
"giftName": "10元代金券",
"id": "",
"mobile": "13800000011",
"number": "",
"userId": "100152996585"
},{
"createTime": "2015-12-21 16:28:57",
"giftLevel": 6,
"giftName": "20元代金券",
"id": "",
"mobile": "13800000011",
"number": "",
"userId": "100152996585"
}
,{
"createTime": "2015-12-21 16:28:57",
"giftLevel": 6,
"giftName": "20元代金券",
"id": "",
"mobile": "13800000011",
"number": "",
"userId": "100152996585"
}
,{
"createTime": "2015-12-21 16:28:57",
"giftLevel": 6,
"giftName": "iphone6",
"id": "",
"mobile": "13800000011",
"number": "",
"userId": "100152996585"
}
],
"status": "1",
"personAwardNum": 0,
"giftName": "10元代金券",
"giftLevel": 6,
"angle": 90
}
);
jquery的each()详细介绍
JS函数的定义与调用方法
js获取键盘事件
原文地址:http://www.35ui.cn/post/20150130456_6812.html 标签:jqueryjsonpajax上一条: Dreamweaver如何代码格式化
下一条: 左右带箭头自动切换代码