我的项目后端使用 PHP 编写,前端使用 Angular.js,服务器由 Apache 在 Linux 中运行。
问题是,任何时候我想重定向到新页面,如 $location.path("/home")
我必须点击 body 上的某个地方才能影响!
或者有时在从 ajx GET 或 POST 方法获取数据时,$scope 已更新,但直到单击 body 上的某处才显示任何内容!
这是路由配置:
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'views/home/home.html',
controller: 'homeControllers',
caseInsensitiveMatch : true
})
.when('/', {
templateUrl: 'views/home/home.html',
controller: 'homeControllers'
})
.otherwise('/')
;
}
]);
这是我的 POST 服务:
app.factory("method", function(primaries) {
return {
POST: function(url, obj, callBack) {
$.ajax({
url: primaries.urls.baseUrl + url,
method: 'POST',
dataType: 'json',
data: obj,
success: function(data) {
if (callBack) {
return callBack(data);
}
return data;
},
error: function(data) {
//console.log('ERROR on ' + url);
},
});
}
}
});
这就是我填充 $scope 的方式:
method.POST("/est/view", {"test":"test"}, function(data) {
$scope.param = data;
})
顺便说一下,我尝试了 $scope.$apply()
但没有任何改变!
我在具有本地数据的 Windows 中的 Localhost 上没有这些问题。
有什么问题!?
最佳答案
其中一些问题很可能源于您使用的是 jQuery 的 $.ajax
而不是 Angular 的 $http.post
。如果您真的想使用 jQuery 的版本,它是可行的,但可能不值得付出努力。
将您的代码更改为:
app.factory("method", function($http, primaries) {
return {
POST: function(url, obj) {
return $http.post(url, obj);
}
}
});
然后在你的 Controller 中:
method.POST("/est/view", {"test":"test"}).then(function(data) {
$scope.param = data;
});
需要注意的是,PHP 不能很好地读取以 JSON
形式发送的 POST
数据,因此您需要让 Angular 以表单数据形式发送,或者用这样的方式读取 JSON POST 数据:
$_JSON = json_decode(file_get_contents('php://input'), true);
if (!empty($_JSON)) {
$_POST = $_JSON;
}
关于javascript - angular & apache - $scope 已更新但需要单击某处才能在界面上显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32101081/