Angular.js,PHP,JSON表单不起作用

时间:2017-04-13 18:45:48

标签: javascript php angularjs json

编辑:表单将触发php代码并导致它将空数据写入我的JSON文件。如何使我的角形式将正确的数据发送到我的PHP代码?

我对angular.js很新,我还没有在php工作过一段时间,但我试图在角度构建一个非常简单的表单,并让它将数据发送到一个php文件然后写入信息到JSON文件。角形式与php和JSON文件位于不同的服务器上。以下是我到目前为止:

索引页:

    <!DOCTYPE html>
<html lang="en" data-ng-app="myApp">
  <head>
    <title>AngularJS Form</title>
    <script type="text/javascript" src="http://code.angularjs.org/1.2.25/angular.min.js"></script>
    <script type="text/javascript" src="js/modules/promise-tracker.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
  </head>
  <body class="container">

  <h2>AngularJs form</h2>

  <p>This is an AngularJs based form. It uses a controller to handle form validation and submission.</p>
  <p>Find a step by step tutorial on this form at <a href="https://www.lullabot.com/blog/article/processing-forms-angularjs">the Lullabot Blog</a>.</p>
  <a href="https://github.com/juampy72/angularjs_form"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub"></a>

  <div data-ng-controller="help">
    <div id="messages" class="alert alert-success" data-ng-show="messages" data-ng-bind="messages"></div>
    <div data-ng-show="progress.active()" style="color: red; font-size: 50px;">Sending&hellip;</div>
    <form name="helpForm" novalidate role="form">
      <div class="form-group">
        <label for="name">Your Name </label>
        <span class="label label-danger" data-ng-show="submitted && helpForm.name.$error.required">Required!</span>
        <input type="text" name="name" data-ng-model="name" class="form-control" required />
      </div>

      <div class="form-group">
        <label for="comments">Description</label>
        <span class="label label-danger" data-ng-show="submitted && helpForm.comments.$error.required">Required!</span>
        <textarea name="comments" data-ng-model="comments" class="form-control" required></textarea>
      </div>

      <button data-ng-disabled="progress.active()" data-ng-click="submit(helpForm)" class="btn btn-default">Submit</button>
    </form>
  </div>

  </body>
</html>

Angular Code:

/**
 * AngularJS module to process a form.
 */
angular.module('myApp', ['ajoslin.promise-tracker'])
  .controller('help', function ($scope, $http, $log, promiseTracker, $timeout) {
    $scope.subjectListOptions = {
      'bug': 'Report a Bug',
      'account': 'Account Problems',
      'mobile': 'Mobile',
      'user': 'Report a Malicious User',
      'other': 'Other'
    };

    // Inititate the promise tracker to track form submissions.
    $scope.progress = promiseTracker();

    // Form submit handler.
    $scope.submit = function(form) {
      // Trigger validation flag.
      $scope.submitted = true;

      // If form is invalid, return and let AngularJS show validation errors.
      if (form.$invalid) {
        return;
      }

      // Default values for the request.
      var config = {
        params : {
          'callback' : 'JSON_CALLBACK',
          'name' : $scope.name,
          'comments' : $scope.comments
        },
      };

      // Perform JSONP request.
      var $promise = $http.jsonp('process.php', config)
        .success(function(data, status, headers, config) {
          if (data.status == 'OK') {
            $scope.name = null;
            $scope.comments = null;
            $scope.messages = 'Your form has been sent!';
            $scope.submitted = false;
          } else {
            $scope.messages = 'Oops, we received your request, but there was an error processing it.';
            $log.error(data);
              console.log($scope.name);
          }
        })
        .error(function(data, status, headers, config) {
          $scope.progress = data;
          $scope.messages = 'There was a network error. Try again later.';
          $log.error(data);
            console.log('name:', $scope.name);
        })
        .finally(function() {
          // Hide status messages after three seconds.
          $timeout(function() {
            $scope.messages = null;
          }, 3000);
        });

      // Track the request and show its progress to the user.
      $scope.progress.addPromise($promise);
    };
  });

Php代码:

<?php

   $myFile = "data.json";
   $arr_data = array(); // create empty array

  try
  {
       //Get form data
       $formdata = array(
          'name'=> $_POST['name'],
          'comments'=> $_POST['comments'],
       );

       //Get data from existing json file
       $jsondata = file_get_contents($myFile);

       // converts json data into array
       $arr_data = json_decode($jsondata, true);

       // Push user data to array
       array_push($arr_data,$formdata);

       //Convert updated array to JSON
       $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

       //write json data into data.json file
       if(file_put_contents($myFile, $jsondata)) {
            //echo 'Data successfully saved';
        }
       else 
            echo "error";

   }
   catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
   }

?>

2 个答案:

答案 0 :(得分:0)

尝试将method="post"添加到表单元素。

<form name="helpForm" novalidate role="form">

<form name="helpForm" novalidate role="form" method="post">

HTML表单默认为GET方法。您正在尝试在PHP脚本中读取POST变量。

   $formdata = array(
      'name'=> $_POST['name'],
      'comments'=> $_POST['comments'],
   );

答案 1 :(得分:0)

因此,为了解决我的问题,我简化了我的代码。我离开我的PHP代码相同,但我最终使用一个简单的HTML表单与页面中的一点点javascript。我的新代码完美无缺,如下所示。

<!DOCTYPE html>
<html>
  <head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>

</head>
<body>

<form id="myForm" action="process.php" method="POST">
    Name:<br>
    <input type="text" name="name">
    <br><br/>

    Message:<br>
    <input type="text" name="comments">
    <br><br>  

    <input type="submit" value="Submit">
</form> 
    <script>
    $('#myForm').on('submit', function(e) {
        e.preventDefault();
        var details = $('#myForm').serialize();
        $.post('process.php', details, function(data) {
            $('index').html(data);
        });
    });
    </script>


</body>
</html>