本文共 2046 字,大约阅读时间需要 6 分钟。
ajax跨域就无法成功获取数据了,需要通过jsonp来处理
报错如下
var targeturl = ajaxurl+"?g=Api&m="+m+"&a="+a; // 跨域地址 $.ajax({ type: "get", url:targeturl, async:false, // 不支持同步,同步无效 dataType:'jsonp', jsonp: "callback", jsonpCallback:"jsonpHandler", data: {}, success:function(json){ } });
这个时候,还不够。依旧无法获取json数据
报错如下原输出格式
protected function printOut() { exit(json_encode($this->outData));}
改为新的格式,加上一个callback
protected function printJsonp() { exit($_GET['callback']."(".json_encode($this->outData).")");}
在XHR中并不能看到
它其实属于js范畴,会自动包裹上回调函数名,
jsonpHandler({ "status":1,"msg":"\u83b7\u53d6\u6210\u529f","info":[{ "id":"1","name":"\u8863\u670d","goods":[{ "goods_id":"1","name":"\u6f02\u4eae\u7684\u8863\u670d","price":"100","logoimg":"http:\/\/image.diandodo.com\/zhudianbao\/Uploads\/User\/u1250000222\/20160723\/201607231342158687.png@250h_250w_1e_1c"},{ "goods_id":"2","name":"\u7f8e\u4e3d\u7684\u8863\u670d","price":"200","logoimg":"http:\/\/image.diandodo.com\/zhudianbao\/Uploads\/User\/u1250000222\/20160723\/201607231342158687.png@250h_250w_1e_1c"}]},{ "id":"2","name":"\u978b\u5b50","goods":[{ "goods_id":"3","name":"\u6f02\u4eae\u7684\u978b\u5b50","price":"100","logoimg":"http:\/\/image.diandodo.com\/zhudianbao\/Uploads\/User\/u1250000222\/20160723\/201607231342158687.png@250h_250w_1e_1c"},{ "goods_id":"4","name":"\u7f8e\u4e3d\u7684\u978b\u5b50","price":"200","logoimg":"http:\/\/image.diandodo.com\/zhudianbao\/Uploads\/User\/u1250000222\/20160723\/201607231342158687.png@250h_250w_1e_1c"}]}]})
jsonp中async无效。要么把操作写在success中,要么写在回调函数中。
// ajax获取接口数据 ajaxGetApiInfo('Home','getCategoryGoods'); function jsonpHandler(json) { if (json.status == '1') { var goods = json.info; var evalText = doT.template($("#category-goods-tmpl").text()); $("#category-goods").html(evalText(goods)); } }本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/5948231.html,如需转载请自行联系原作者