当我使用$http将angularJS与我的PHP服务器端脚本连接时,我遇到了一个问题。
我的$http看起来像这样
$http.get('http://www.muslimsquare.com/sandbox/user_login.php', {"userID":'123456'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
alert(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert(data)
});
如您所见,我尝试将带有值123456的用户ID传递给我的服务器。 我的PHP脚本是这样的
<?php
echo 'userID is'.$_GET['userID'];
?>
它只是将用户 ID 响应回客户端。
当我运行此代码时,它只显示我
用户标识为
没有用户 ID 返回到客户端。
我的代码出了什么问题。
知道如何解决这个问题吗?
谢谢。
这个 http 请求是异步的。这意味着,尝试这种方法:在服务函数中调用此函数
promise = $http({
url: "http://your.url.com/service.php",
method: "POST",
data: {"data":data}
}).then(function(response) {
// The then function here is an opportunity to modify the response
// The return value gets picked up by the then in the controller.
return response.data;
});
// Return the promise to the controller
return promise;
在控制器中调用服务,如下所示:
Service.getData(data).then(function(returnedData) {
$scope.data = returnedData;
});
从服务返回的数据现在位于 $scope.data 中,并将在前端显示 {{data.value}}
希望这有帮助
这是我如何使用 htttp 方法,
$http({method: 'get', url: 'http://www.muslimsquare.com/sandbox/user_login.php?userID=123456'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
alert(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert(data)
});
错误不在于角度,而在于
XMLHttpRequest cannot load http://www.muslimsquare.com/sandbox/user_login.php?userID=123456. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access. index.html:1
null
您尝试连接的服务器已为其他服务器禁用它以防止跨脚本,要禁用此功能,您需要在user_login.php中设置标头
将其添加到 php 文件的顶部
header('Access-Control-Allow-Origin: *');
然后试试这个代码笔
嘿,
你的第一个代码是正确的,尽管它的目的是获取 JSON 数据。
<?php
echo 'userID is'.$_GET['userID'];
?>
这不会输出 JSON
如果您还没有找到解决方案,请尝试此操作
$userId = $_GET['userID'];
echo '{"userID ":$userId}';
然后在获取端
$http.get('test.php', { params:{ "userID": 2, "name": "yourNameIfAny" } }).then(function(resp){
console.log('Success', resp);
// For JSON responses, resp.data contains the result
$scope.conditions = resp.data.userID;
$ionicPopup.confirm({
title: 'Json Responce',
template: resp.data.userID
});
confirmPopup.then(function(res) {
if(res) {
console.log('You are sure');
} else {
console.log('You are not sure');
}
});