简体   繁体   中英

How to access data submitted by a form in Angularjs?

Here is an example from Ng-Book - the Complete Book on Angularjs Book by Ari Lerner http://jsbin.com/voxirajoru/edit?html,output where ng-form has been used to create nested form elements and perform validation. As the each input field has same value for name attribute so how can on the server side I can access value of all three variables by using some server side language? Let's say it's PHP and method is post . Usually in PHP I would do this:

`$_POST['dynamic_input']`

but how is it possible to access three field values coming from input field using $_POST array?

Using the example from the link you provided, you can access form data by updating the code there with the following.

// Add the fields object as a parameter to submitForm()

<form name="signup_form" ng-controller="FormController" ng-submit="submitForm(fields)" novalidate>

// In the $scope.submitForm() function...

$scope.submitForm = function(data) {
    alert(data[0].name); // Alerts name
    alert(data[1].name); // Alerts password
    alert(data[2].name); // Alerts email
  };

If you log out the data received by submitForm(), you get the following:

[{"placeholder":"Username","isRequired":true,"$$hashKey":"004","name":"random name"},{"placeholder":"Password","isRequired":true,"$$hashKey":"005","name":"password"},{"placeholder":"Email (optional)","isRequired":false,"$$hashKey":"006","name":"email@host.com"}]

For passing to your server, package all this up as is or format it to your preference and send it to your server via the built in $http.post() or $resource() inside of the $scope.submitForm function.

An example of the formatted data could be:

$scope.submitForm = function(data) {
    var postData = {};
    postData.name = data[0].name;
    postData.password = data[1].name;
    postData.email = data[2].name;

    ... send postData to server via AJAX ...

    // Creates the object: {"name":"random name","password":"password","email":"email@host.com"}
    //alert(JSON.stringify(postData));
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM