【问题标题】:angular js sending empty data to php using post methodangular js使用post方法将空数据发送到php
【发布时间】:2017-12-07 02:59:31
【问题描述】:

我正在制作一个测试应用程序来测试角度和 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 中获取非对象的属性

通知:试图在C:\xampp\htdocs\test\test.php中获取非对象属性上线6
字符串”

但是 Angular 正在发送数据 数据:对象 年龄:“2” 名称:“abcd” 无法确定问题出在哪里。

【问题讨论】:

  • 我不是 100% 确定,但不应该是 $name = $_POST['name']; $age = $_POST['年龄']; ....
  • "
    注意:未定义索引:C:\xampp\htdocs\test\test.php 中的名称 行>5

    注意:未定义索引:C:\xampp\htdocs\test\test.php上线6
    字符串"
  • 现在收到此错误。这个方法也试过了。

标签: javascript php angularjs xampp


【解决方案1】:

向 php 发出正确的 post 请求的一种方法是通过 $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});

【讨论】:

  • OP 正在使用 json_decode(file_get_contents('php://input')) 解码内容类型 application/json。
  • ReferenceError: $httpParamSerializerJQLike 未定义
  • 你必须把它注入到控制器中,在$http旁边,app.controller('myctrl',function($scope,$http, $httpParamSerializerJQLike)
猜你喜欢
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多