[英]angular js sending empty data to php using post method
我正在做一個測試應用程序來測試角度和PHP數據傳輸。 但是Angular通過post方法發送數據,但是php不接受數據
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myctrl">
<form ng-submit="insert()">
<input type="text" ng-model="name" name="name" placeholder="name">
<input type="age" ng-model="age" name="age" placeholder="age">
<button type="submit">Submit</button>
</form>
</div>
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.controller('myctrl',function($scope,$http){
$scope.insert=function(){
$http.post("test.php", {
'name':$scope.name,
'age':$scope.age
}).then(function(response){
console.log(response);
},function(error){
alert("Sorry! Data Couldn't be inserted!");
console.error(error);
});
}
});
</script>
</body>
</html>
這是html代碼php代碼是
<?php
$data = json_decode(file_get_contents('php://input'));
$place=$data->name;
$image=$data->age;
echo $place;
echo $image;
echo "string";
?>
當我訪問這些名稱和年齡時,給出的錯誤為
“
注意 :嘗試在第5行的C:\\ xampp \\ htdocs \\ test \\ test.php中獲取非對象的屬性
注意 :嘗試在第6行的C:\\ xampp \\ htdocs \\ test \\ test.php中獲取非對象的屬性
串”
但是angular正在發送數據data:Object age:“ 2” name:“ abcd”無法確定問題出在哪里。
向php發出正確的發布請求的一種方法是通過$ httpParamSerializerJQLike,
這樣您就可以發布這樣的信息:
var data = {
'name':$scope.name,
'age':$scope.age
};
var req = {
method : "POST",
url: "http://yourUrl",
data: $httpParamSerializerJQLike(data),
headers: {
'Content-Type': "application/x-www-form-urlencoded"
}
};
$http(req).then(function(resp){//success}).catch(function(error){//error});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.