【问题标题】:Angular form submission not displaying results from PHPAngular 表单提交不显示 PHP 的结果
【发布时间】:2016-02-22 14:39:35
【问题描述】:

我正在尝试显示提交表单的结果,AngularJS > PHP > Back 但我什么也没得到。我尝试了很多不同的方法,根据所有谷歌的说法,我做得对,但控制台日志只是说它是未定义的。

这里是提交函数:

$scope.testProcessForm = function() {
        $http({
      method  : 'POST',
      url     : 'test.php',
      data    : $scope.formData,
      headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'} 
     })
      .success(function(data) {
        if (data.errors) {
          // Showing errors.
          $scope.errorselectedServices = data.errors.selectedservices;
          $scope.errorincEmail = data.errors.incemail;
        } else {
          $scope.submissionMessage = data.messageSuccess;
          $scope.test= data.test;

PHP:

$data['test'] = $test;
echo json_encode($data);

HTML:

    <div ng-show="test">{{test}}</div>

为什么我得到“测试未定义”并且没有 div?如果我在 PHP 中添加回显,我会得到正确的回复。经过一些调试,它似乎没有挂在代码中的任何地方。我做错了什么?

// app.js
// create our angular app and inject ngAnimate and ui-router 
// =============================================================================
angular.module('formApp', ['ngAnimate', 'ngMessages', 'ui.router'])

// configuring our routes 
// =============================================================================
.config(function ($stateProvider, $urlRouterProvider) {
    
    $stateProvider
    
        // route to show our basic form (/form)
        .state('form', {
            url: '/form',
            templateUrl: 'form.html',
            controller: 'formController'
        })
        
        // nested states 
        // each of these sections will have their own view
        // url will be nested (/form/profile)
        .state('form.tjanst', {
            url: '/tjanst',
            templateUrl: 'form-tjanster.html'
        })
        
        // url will be /form/interests
        .state('form.epost', {
            url: '/epost',
            templateUrl: 'form-epost.html'
        })
    
    
        // url will be /form/payment
        .state('form.fax', {
            url: '/fax',
            templateUrl: 'form-fax.html'
        })
        
            // url will be /form/payment
        .state('form.sms', {
            url: '/sms',
            templateUrl: 'form-sms.html'
        })
    
            // url will be /form/payment
        .state('form.mcl', {
            url: '/mcl',
            templateUrl: 'form-mcl.html'
        })
    
            // url will be /form/payment
        .state('form.review', {
            url: '/review',
            templateUrl: 'form-review.html'
        });
        
    // catch all route
    // send users to the form page 
    $urlRouterProvider.otherwise('/form/tjanst');
})

.value('formSteps', [
  {uiSref: 'form.tjanst', valid: false},
  {uiSref: 'form.epost', valid: false},
  {uiSref: 'form.fax', valid: false},
  {uiSref: 'form.sms', valid: false},
  {uiSref: 'form.mcl', valid: false},
  {uiSref: 'form.review', valid: false}
])

 .run([
            '$rootScope',
            '$state',
            'formSteps',
            function($rootScope, $state, formSteps) {
              
              // Register listener to watch route changes
                $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
                    
                    var canGoToStep = false;
                    // only go to next if previous is valid
                    var toStateIndex = _.findIndex(formSteps, function(formStep) {
                      return formStep.uiSref === toState.name;
                      
                    });
                    
                    console.log('toStateIndex',toStateIndex)
                    if(toStateIndex === 0) {
                      canGoToStep = true;
                    } else {
                      canGoToStep = formSteps[toStateIndex - 1].valid;
                    }
                    console.log('canGoToStep', toState.name, canGoToStep);
                    
                    // Stop state changing if the previous state is invalid
                    if(!canGoToStep) {
                        // Abort going to step
                        event.preventDefault();
                    }
                });
            

            }


        ])

// our controller for the form
// =============================================================================
.controller('formController', function($scope, $state, $http, formSteps) {
    
    // we will store all of our form data in this object
    $scope.formData = {};
    $scope.submission = false;
    $scope.formStepSubmitted=false;
    $scope.formData.selectedServices = {};
    $scope.messitServices = [{'name':'Fax', 'id':1}, {'name':'SMS', 'id':2}, {'name':'Minicall', 'id':3}];
    
    $scope.someSelected = function (object) {
      return Object.keys(object).some(function (key) {
        return object[key];
      });
    };
    
    var nextState=function(currentState) {
      switch (currentState) {
          case 'form.tjanst':
              return 'form.epost'
              break;
          case 'form.epost':
              return 'form.fax'
              break;
          case 'form.fax':
              return 'form.sms'
              break;
          case 'form.sms':
              return 'form.mcl'
              break;
          case 'form.mcl':
              return 'form.review'
              break;
          default:
              alert('Did not match any switch');
      }
    };
    
    var updateValidityOfCurrentStep=function(updatedValidity) {
      var currentStateIndex = _.findIndex(formSteps, function(formStep) {
          return formStep.uiSref === $state.current.name;
        });
        
        formSteps[currentStateIndex].valid = updatedValidity;
    };
    
    $scope.goToNextSection=function(isFormValid) {
      console.log('isFormValid ', isFormValid);
      // set to true to show all error messages (if there are any)
      $scope.formStepSubmitted = true;
      if(isFormValid) {
        // reset this for next form
        $scope.formStepSubmitted = false;
        
        // mark the step as valid so we can navigate to it via the links
        updateValidityOfCurrentStep(true /*valid */);
        
        $state.go(nextState($state.current.name));
      } else {
        // mark the step as valid so we can navigate to it via the links
        updateValidityOfCurrentStep(false /*not valid */);
      }
    };
    
    $scope.testProcessForm = function() {
            $http({
          method  : 'POST',
          url     : 'kundreg.php',
          data    : $scope.formData,
          headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'} 
         })
          .success(function(data) {
            if (data.errors) {
              // Showing errors.
              $scope.errorselectedServices = data.errors.selectedservices;
              $scope.errorincEmail = data.errors.incemail;
            } else {
              $scope.submissionMessage = data.messageSuccess;
              $scope.faxSenderPhoneNo = data.faxSenderPhoneNo;
              $scope.faxSender = data.messit.faxSender;
                console.log(faxSender);
 //             $scope.formData = {};
            }
        });
    };
        
});
<!DOCTYPE html>
<h3 class="text-center">Granskning</h3>
<h4 class="text-center">Vänligen kontrollera:</h4><br>
<div class="form-group row"></div>
<!--    <span ng-show="errorselectedServices">{{errorselectedServices}}</span>
    <span ng-show="errorincEmail">{{errorincEmail}}</span>></div> -->
    <div ng-show="faxSender">{{ faxSender }} ng show faxsenderphoneno</div>
<br>
<div class="form-group row">
    <div class="col-xs-6 col-xs-pull">
    <a ui-sref="form.fax" class="btn btn-block btn-info">
    Föregående <span class="glyphicon glyphicon-circle-arrow-left"></span></a>
    </div>
    <div class="col-xs-6 col-xs-push">
    <a ng-click="testProcessForm()">
    Skapa <span class="glyphicon glyphicon-circle-arrow-right"></span>
    </a>
    </div>
</div>


<?php
$errors = array();
$data = array();
$selectedServices = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);

// checking for blank values.
if (empty($_POST['selectedServices']))
  $errors['selectedServices'] = 'Minst en tjänst måste väljas.';

if (empty($_POST['incEmail']))
  $errors['incEmail'] = 'Epost som tillåts använda tjänsterna saknas';

  $selectedServices = $_POST['selectedServices'];


if (!empty($errors)) {
  $data['errors']  = $errors;
} else {
        if (!empty($_POST["faxSenderPhoneNo"])) {
                // ta bort allt som inte är siffror
                $faxSender = preg_replace('/[^0-9\/+]/', '', $_POST["faxSenderPhoneNo"]);
                // finns ingen nolla så lägger vi till den så vi kan matcha den i regexen
                 //regex med internationellt format så databasen blir glad
                if (preg_match('/^0/', $faxSender) === 0) {
                    $faxSender = "0{$faxSender}";
                }
                $faxSenderPhoneNo = preg_replace("/(^0|^46)/", "+46", $faxSender);
                $messit['faxSender'] = $faxSenderPhoneNo;
        }
        else {
            $faxSenderPhoneNo = 'NULL';
        }
        if (!empty($_POST["deliveryReportFax"])) {
            $deliveryReportFax = $_POST["deliveryReportFax"];
        }
        else {
            $deliveryReportFax = '3';
        }
        
    }

}

if (!$error) {
   // sql
echo json_encode($data);
?>

【问题讨论】:

  • 这不是您检索 POST 数据的方式。
  • 你能发布完整的代码吗?
  • 尝试使用 console.log() 方法检查成功函数中的 var 数据是否返回您认为返回的内容。
  • 添加了更多代码。我试过控制台日志,但如上所述,它返回为“未定义”,我不知道为什么。

标签: javascript php angularjs forms


【解决方案1】:

我发现了错误。显然你必须将变量引用到数组中; $data['faxSender'] = "$faxSenderPhoneNo";

现在按预期工作。

编辑: 好吧,它起到了一定的作用。我的 div 仍然没有显示。使用 console.log(data) 登录后,我可以看到我有很多未定义的索引,但我的数据数组在那里,所以我不明白为什么我无法访问它。

我修复了未定义的东西,然后突然显示每个 div。不知道为什么 PHP 决定将所有这些信息转储到我的 $data 数组中。

第二次编辑:显然 .success 已被弃用。使用 .then 代替 error_reporting(1);似乎总是给我一个数组,其中包含 angular 然后可以使用的数据。

【讨论】:

    【解决方案2】:

    由于您是 php 文件中的 JSON 编码数据,因此文件返回一个字符串。因此,您首先需要将 JSON 解码为 Java 脚本对象。此外,您 $http 返回 Angular Promise($q 服务)。我不确定使用

    .成功

    方法。而是使用

    .那么

    .then(function successCallback(response) {
      // this callback will be called asynchronously
      // when the response is available
      // decode JSON firs since you are sending JSON from PHP
      var data = JSON.parse(response);
      $scope.test = data.test;
    }, function errorCallback(response) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
      // Handle error here
    });
    

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多