簡體   English   中英

角表單提交不顯示PHP的結果

[英]Angular form submission not displaying results from PHP

我正在嘗試顯示提交表單AngularJS> PHP> Back的結果,但是我什么也沒得到。 我已經嘗試了許多不同的方法,並且根據所有Google的說法,我都做對了,但是控制台日志只是說這是未定義的。

這是提交功能:

$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>

為什么我會得到“ test is undefined”並且沒有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); ?> 

我發現了錯誤。 顯然,您必須將變量引用到數組中。 $ data ['faxSender'] =“ $ faxSenderPhoneNo”;

現在按預期工作。

編輯:好吧,它工作到了一定程度。 我的div仍然沒有顯示。 使用console.log(data)登錄后,我可以看到我有很多未定義的索引,但是我的數據數組在那里,所以我不明白為什么我無法訪問它。

我修復了未定義的內容,然后突然顯示了每個div。 不知道為什么PHP決定將所有信息轉儲到我的$ data數組中。

第2次修改:顯然不建議使用.success。 使用.then代替error_reporting(1); 似乎總是給我一個數組,然后角度可以使用的數據。

由於您是php文件中的JSON編碼數據,因此文件返回一個String。 因此,您首先需要將JSON解碼為Java腳本對象。 另外,您$ http返回角度承諾($ 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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM