AngularJS下jsonp跨域SyntaxError问题
2017-01-20 20:10
183 查看
AngularJS下jsonp跨域missing ; before statement的问题
今天下午帮忙写一段AngularJS的代码,其中用到了跨域请求json。首选当然是$http.jsonp。使用规则
指定callback和回调函数名函数名为JSON_CALLBACK时,会调用success回调函数,JSON_CALLBACK必须全为大写
使用jsonp时,返回的数据必须为严格的json格式
示例代码
$scope.getJobs = function () { url = 'http://localhost:8082/test.php?callback=JSON_CALLBACK'; $http.jsonp(url) .success(function (response) { console.log('Get Jenkins Jobs OK') $scope.lists = response.data; }) .error(function (data, status) { console.log('Get Jenkins Jobs Bad') }); };
出现的问题
由于原来的后台在家里无法访问,所以模仿json数据格式自己用php写了个后台,架在http://localhost:8082上,直接将json数据echo出来。php后台的代码:
<?php $json = '{"code": 200, "message": "OK"}'; echo $json; ?>
访问后就像下面这样
{ “code”: 200, “message”: “OK” }
写完后发现怎么也读不出来返回的json数据。打开控制台,发现报错SyntaxError: missing ; before statement
百思不得其解。上网查也没查出个所以然,只知道是json格式出了毛病,但是将json串放到json检测工具上去,的确是严格的json格式。
最后看来官方文档
Relative or absolute URL specifying the destination of the request.
The name of the callback should be the string JSON_CALLBACK.
总算明白了,返回的json必须是这种格式
JSON_CALLBACK({ json数据 })
总算搞明白了
于是换成这样写
php后台代码:
<?php $callback = $_GET['callback']; $json = '{"code": 200, "message": "OK"}'; echo "$callback($json)"; ?>
得到的数据是这样的
JSON_CALLBACK({“code”: 200, “message”: “OK”})
这次可以读出来了,完全没有问题。
相关文章推荐
- AngularJS 用 $http.jsonp 跨域SyntaxError问题
- AngularJS中$http.jsonp跨域请求问题
- AngularJs最简单解决跨域问题jsonp案例
- 前端与服务器分离开发出现跨域问题,jsonp与gulp-connect注意点,angularjs改造
- AngularJs 服务之jsonp解决跨域问题
- AngularJS 用 $http.jsonp 方法跨域请求数据错误的问题
- AngularJs服-jsonp解决跨域问题
- AngularJS中$http.jsonp跨域请求问题
- AngularJS中$http.jsonp跨域请求问题
- AngularJs中的JSONP跨域访问数据传输问题
- AngularJS 用 $http.jsonp 方法跨域请求数据错误的问题
- 详解Jquery和AngularJs,Servlet中jsonp解决跨域问题(转)
- jsonp 跨域 Uncaught SyntaxError: Unexpected token : 的问题
- 使用jQuery与JSONP解决跨域问题
- jsonp和java联合使用解决跨域问题
- JSONP(处理跨域问题)
- 用jQuery与JSONP来解决跨域访问的问题
- JSONP解决跨域取数据的问题
- 深入浅出JSONP:解决AJAX跨域问题
- 用jQuery与JSONP轻松解决跨域访问的问题