AngularJS和PHP Undefined属性:stdClass

时间:2015-09-30 13:26:42

标签: javascript php angularjs

我有一个简单的POST http请求,但收到错误Undefined property: stdClass::$messageangular .module('smsApp') .controller('smsController', smsController) .config(config); function config($routeProvider) { $routeProvider .when('/', { controller: 'smsController', templateUrl: 'app/views/messageForm.html' }); } function smsController($scope, $http) { $scope.sendMessage = function() { $scope.loading = true; $scope.smsForm = { number: undefined, message: undefined }; var data = { number: $scope.smsForm.number, message: $scope.smsForm.message }; var req = { method: 'POST', url: 'app/endpoints/sendsms.php', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: data }; $http(req) .then(function successCallback(response) { console.log(response); $scope.loading = false; }, function errorCallback(response) { console.log(response); }); } } 。这是我的代码:

smsController.js

<div ng-hide="loading">
  <div class="input-field col s12">
    <input type="text" ng-model="smsForm.number" maxlength="11">
  </div>
  <div class="input-field col s12">
    <textarea ng-model="smsForm.message" maxlength="200"></textarea>
    <button ng-click="sendMessage()">Send</button>
  </div>
</div>

messageForm.html

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo json_encode($request);

sendsms.php

imagefilledrectangle

控制台 enter image description here

没有传递数据,我收到了未定义的属性错误。我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:1)

您在undefined函数中设置了sendMessage(),这将覆盖用户输入的任何值...以便将发送的内容。

将模型对象的声明更改为在函数外部,以便它将被子作用域继承:

$scope.sendMessage = function() {
    $scope.loading = true;
    $scope.smsForm = {
        number: undefined,
        message: undefined
    };
    ....
    // ajax code 
 }

 $scope.smsForm = {};

 $scope.sendMessage = function() {
    $scope.loading = true;

    ....
    // ajax code
 }

ng-model会自动将属性添加到$scope.smsForm对象,这就是为什么它在这里被声明为空对象的原因。

此外,由于$scope.smsForm具有api所需的属性,因此无需将它们转移到新对象data

$http.post('app/endpoints/sendsms.php', $scope.smsForm ).then(...