<html lang="en" ng-app="myApp"><head><meta charset="UTF-8"><title>Title</title><!--<script src="../js/jquery-1.11.0.js"></script>--><script src="angular.min.js"></script><script>angular.module("myApp",[]).controller("test",["$scope","$http",function($scope,$http){$http.get("http://datainfo.duapp.com/shopdata/getGoods.php?classID=1").success(function(response){$scope.myarr = response.sites;})}])</script></head><body><div ng-controller="test"><ul><li ng-repeat="data in myarr"><img src="{{data.goodsListImg}}"/><p>名称:<span>{{data.goodsName}}</span></p><p>价格:<span>{{data.price|currency:"¥"}}</span></p></li></ul></div></body></html>出现的问题
这个是浏览器的跨域造成的,之前的学习中我也不是很清楚这个,只是知道由于不是在同一个域名下面访问的此域名下的资源就会造成跨域。其实之前看到这个是以为请求的格式有问题,返回的json数据到不了。
下面是json格式返回的数据。
按照她给我的URL,我发现在json数据前面有一个callback,这个是php中的回调函数,结果网上一搜发现get请求对于这种回调函数是没有作用的。
解决办法
必须使用下面的这种办法来处理这种有callback的jsonp格式的数据。
<script>var myApp = angular.module("App", []);myApp.controller("test", function($scope, $http) {// 回调函数用法myUrl = "http://datainfo.duapp.com/shopdata/getGoods.php?callback=JSON_CALLBACK";$http.jsonp(myUrl).success(function(response) {console.log(response);});});</script>注意两点:
<!DOCTYPE html><html ng-app="App"><head><meta charset="UTF-8"><title>Title</title><script src="angular.min.js"></script><script>var myApp = angular.module("App", []);myApp.controller("test", function($scope, $http) {// 回调函数用法myUrl = "http://datainfo.duapp.com/shopdata/getGoods.php?callback=JSON_CALLBACK";$http.jsonp(myUrl).success(function(response) {console.log(response);$scope.myarr = response;});});</script></head><body><div ng-controller="test"><ul><li ng-repeat="data in myarr"><!--scr里面的angularJS不可以这样写--><img src="{{data.goodsListImg}}" /><p>名称:<span>{{data.goodsName}}</span></p><p>价格:<span>{{data.price|currency:"¥"}}</span></p></li></ul></div></body>
自动将我们的JSON_CALLBACK替换成了下面的字符,这应该是AngularJS替换的。
引用
跨域是如何解决的:
通过json来传递数据,靠jsonp来跨域,json是一种数据交换格式,而jsonp是一种靠开发人员的聪明才智创造的一种非官方跨域数据交互协议;
JSONP是如何产生的:
这个解释足以理解跨域问题和为什么需要使用JSONP?
以上就是本文的全部内容,希望对大家有所帮助,同时也希望多多支持脚本之家!