在使用离子post方法将数据发送到服务器(Sending data to a server usin

2019-09-29 17:44发布

我想数据与POST方法从离子发展发送到服务器,问题是我不明白poque不行。

指数

<ion-view view-title="Guardar estudiante">
  <ion-content class="padding">
<form>
  <div class="list">

    <label class="item item-imput">
      <input type="number" placeholder="Documento" ng-model="Usuario.idu">
    </label>


    <label class="item item-imput">
      <input type="text" placeholder="Nombre" ng-model="Usuario.nom">
    </label>
    <label class="item item-imput">
      <input type="text" placeholder="Apellidos" ng-model="Usuario.ape">
    </label>

    <label class="item item-imput">
    <input type="text" placeholder="Direccion" ng-model="Usuario.dir"> 
    </label>

    <label class="item item-imput">
           <input type="number" placeholder="Telefono" ng-model="Usuario.tel">  
    </label>

    <label class="item item-imput">
    <input type="text" placeholder="Email" ng-model="Usuario.cor"> 
    </label>

    <label class="item item-imput">
           <input type="text" placeholder="Contraseña" ng-model="Usuario.pas">
    </label>



    <label class="item item-input">
      <span style="text-align: center; width: 100%;">
         <button 
         class="button icon-left" ng-click="guardarEstudiante()">
         GUARDAR 
         </button> 
      </span>
    </label>
  </div>
</form>

<p ng-repeat='u in users'>{{u.Nombre}} </p>
<p>{{ PostDataResponse }}</p>

Controller.js

angular.module('starter.controllers', [])    
.controller('GuardarEstudianteCtrl',    
   function($scope, $http){
  $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-    urlencoded;charset=utf-8';
var defaultHTTPHeaders = {
  'Content-type': 'application/json',
  'Accept' : 'application/json'
};
$http.defaults.headers.post = defaultHTTPHeaders;
  $scope.Usuario =
{
     idu : '',
     nom : '',
     ape : '',
     dir : '',
     tel : '',
     cor : '',
     pas : '' 
};
  $scope.guardarEstudiante = function(){
       // alert($scope.Usuario.Apellidos)
   var urlCompleta = 'http://www.******.co/*******.php?';
   //var postUrl     = $sce.trustAsResourceUrl(urlCompleta);

   UsuarioObj  = $scope.Usuario;

   $http.post(urlCompleta, $scope.Usuario)

   .then(

        function(data, status, headers, config){
          if (data.data.success  != 1){

           alert('Error En Registro, '+ data.data.message+" Success-->     "+data.data.success+" \n user ="+ $scope.Usuario.nom+" \napellido "+$scope.Usuario.ape);
      }
     else
     {
      alert('Usuario Registrado, '+ data.data.message+" Success-->     "+data.data.success+" \n user ="+ $scope.Usuario.nom );
     }

         console.log('Error with the API list_mobile_project');
         console.log(data);
         console.log(status);
         console.log(headers);
         console.log(config);  

           $scope.users = UsuarioObj;
           console.log("-------------User------------")
           console.log($scope.users);

        },
        function(data, status, headers, config){
          alert('Error De Codigo o de plataforma de salida de datos');

          $scope.users = UsuarioObj;
           console.log("-------------User------------")
           console.log($scope.users);

        }
    ); 
  };
    });

PHP

<?php

if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        
            {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }




/*
 * Following code will update a product information
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();

// check for required fields
// check for required fields

if (isset($_POST['idu'])
&& isset($_POST['nom']) 
&& isset($_POST['ape'])
&& isset($_POST['dir'])
&& isset($_POST['tel'])
&& isset($_POST['cor'])
&& isset($_POST['pas'])
) 
{

$idus = $_POST['idu'];
$nomb = $_POST['nom'];
$apel=$_POST['ape'];
$dire=$_POST['dir'];
$tele=$_POST['tel'];
$corr=$_POST['cor'];
$pass=$_POST['pas'];

  // include db connect class
   $con = mysqli_connect("localhost","******","*******","******");

// mysql inserting a new row
$result = mysqli_query($con,"INSERT INTO ******(Id***, N****, A***, D****, T****, E*****, C****, E****) VALUES($idus,'$nomb', '$apel','$dire', $tele, '$corr','$pass','Inactivo')");


 // check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
    echo json_encode($response);
    } else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}


?>

Answer 1:

您好尝试此POST数据。

 $.ajax({
           type: "POST",
           url: '' + globURL + 'addgcm.php?user_id='+userId+'&gcm_id='+e.regid+'',
           cache: false,
           success: function(result){

                               }
        });   


Answer 2:

试试这个使用JSON.stringify()

$http.post(urlCompleta, JSON.stringify($scope.Usuario))

要么

$http({
   url : urlCompleta,
   method : "POST",
   data : JSON.stringify($scope.Usuario)
}).then(function(responseData){
    //success
  }, function(errorData){
    //error
  })


Answer 3:

我使用此代码,可与各种方法GET / POST / DELETE

$http({
       method: method,//GET-POST
       url: url,
       data: data,
       dataType: 'json',
       headers: {
           "Content-Type": "application/json"
       }
}).success(function (data) {//Success handling

}).error(function (data, status) {//Error handling

});

问候。



文章来源: Sending data to a server using post method in ionic