您好我试图通过Phonegap应用程序从我的服务器上的MySQL数据库获取数据。我正在服务器上调用一个php文件给我回JSON。我试图在服务器上的php文件上进行ajax调用,我想将json数据保存在$ scope范围内,以便我可以在我的HTML中使用它。我的脚本看起来像这样:
function PostsCtrlAjax($scope, $http)
{
var output2 = $('#output2');
$.ajax({
url: 'http://myWebsiteMySQL.ch/landmarks.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$scope.posts = data;
},
error: function(){
output2.text('There was an error loading the data.');
}
});
}
</script>
然后我想访问html文件中的$ scope数据,如下所示:
<div id="ng-app" ng-app ng-controller="PostsCtrlAjax">
<div ng-repeat="post in posts" class='postBody'>
<div>{{post.id}}</div>
<div>{{post.name}}</div>
</div>
</div>
但我看不到任何数据。我究竟做错了什么? 我感谢任何帮助。我试图在2天后解决这个问题。
我在服务器上的php文件如下所示:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xx";
$password = "xx";
$database = "xx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude, l_image AS bild FROM landmarks ORDER BY l_name";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
发回的数据是:
([{"id":"14","name":"Fashion_Coupons","latitude":"9.000000000000","longitude":"9.000000000000","bild":null},{"id":"13","name":"Travel_Coupons","latitude":"3.000000000000","longitude":"4.000000000000","bild":"TopTrendsProgressbar.png"},{"id":"31","name":"Travel_Coupons","latitude":"222.000000000000","longitude":"23212.000000000000","bild":null}]);
答案 0 :(得分:1)
添加观察方法以检测更改&#39;帖子&#39;在你的模型中,像这样:
$scope.$watch('_rows', function() {
$scope.items = $scope.posts;
});
答案 1 :(得分:0)
有关如何以角度进行JSONP请求,请参阅此答案。 AngularJS 1.2 cross origin requests are only supported for HTTP
请注意,文档说JSONP URL必须包含字符串JSON_CALLBACK。 http://code.angularjs.org/1.1.5/docs/api/ng。$ HTTP#JSONP
$http.jsonp('http://myWebsiteMySQL.ch/landmarks.php?callback=JSON_CALLBACK')
.success(function (data)
{
$scope.posts = data;
});
您可以添加错误回调以查看是否包含任何有用的信息。在.success回调之后链接.error。
$http.jsonp('http://myWebsiteMySQL.ch/landmarks.php')
.success(function (data) { ... })
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});