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”})
这次可以读出来了,完全没有问题。