如何将表单数据从Ionic 3传递到PHP文件?

3

我希望将Ionic 3中的表单数据传递给位于本地主机上的PHP文件。 以下是我的Ionic按钮代码:

createEntry(name, description)
{
 let body    : string   = "testname=" + name + "&testval=" + description,
     type     : string   = "application/x-www-form-urlencoded; charset=UTF-8",
     url      : any      = this.baseURI + "manage-data.php",
     method : 'POST',
     headers  : any      = new Headers({ 'Content-Type': 'application/json' }),
     options  : any      = new RequestOptions({ headers: headers });

     alert(url);  //Output: http://localhost:1432/ionic-php-sql/manage-data.php
     alert(body); //Output: name=Test&description=Test
     alert(options); //[object Object]
     console.log(options);

     this.http
     .post(url, body)
     .subscribe(
         data => {
           console.log(data);
           alert(data);
           alert('success');
              if(data.status === 200)
               {
                  this.hideForm   = true;
                  this.sendNotification(`Congratulations the technology: ${name} was successfully added`);
               }
         },
         err => {
           console.log("ERROR!: ", err);
           alert(err);
         }
     );
}

这是我的 PHP 文件代码:

 <?php
     header('Access-Control-Allow-Origin: *');
     header('Access-Control-Allow-Headers: X-Requested-With');
     header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

     $con = mysqli_connect("localhost","root","","ionic_test");

     // Check connection
     if (mysqli_connect_errno())
     {
         echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
      else
      {
         echo "success !";
         if($_SERVER['REQUEST_METHOD']=='post')
         {
            echo "posting";
            $postdata = file_put_contents("php://input");
            $request = json_decode($postdata);
            var_dump($request);

            $name = $_POST["testname"];
            $desc = $_POST["testval"];

            $sql  = "INSERT INTO ionictest(testname, testval) VALUES ($name,$desc)";
            $stmt    = mysqli_query($con, $sql);
        }
     }
 ?>

请检查代码,如果有任何错误,请告诉我。 我想从Ionic传递数据到Php文件,然后将其存储到mysql数据库中。 我已经成功地建立了php和mysql数据库之间的连接,但是我无法将数据从Ionic表单传递到php中,虽然它没有显示任何错误。 谢谢。
2个回答

2

我解决了我的问题! Ionic按钮点击代码:

submitEntry(name, description)
{
    var link = this.baseURI + "manage-data.php";
    var body = JSON.stringify({testname: name, testval: description});

    alert("DATA: "+body);

    this.http.post(link, body)
    .subscribe(data => {
         console.log("DATA:", data);
         this.hideForm   = true;
         this.sendNotification(`Congratulations the technology: ${name} was successfully added`);
    },
         err => {
         console.log("ERROR!: ", err);
         alert(err);
    });
}

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);
    }

    $postdata = file_get_contents("php://input");
    if(isset($postdata))
    {
        $request = json_decode($postdata);
        $name = $request->testname;
        $desc = $request->testval;

        if($name != "" && $desc != "")
        {
            $con = mysqli_connect("localhost","root","","ionic_test");

            // Check connection
            if (mysqli_connect_errno())
            {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }
            else
            {
                echo "Name: " .$name;
                echo "Desc: " .$desc;

                $sql  = "INSERT INTO ionictest(testname, testval) VALUES ('$name', '$desc')";
                $stmt = mysqli_query($con, $sql) or die ("MySQL Error:".mysqli_error($con));

                echo "successfully inserted !";
            }
        }
        else 
        {
            echo "Empty name and description parameter!";
        }
    }
    else 
    {
        echo "Not called properly with name and description parameter!";
    }
 ?>   

如果有人需要,您可以参考这段代码... :)

1

对我来说,在本地测试过并且运行良好的最简单方法是...

在php文件中:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
require_once "../vendor/autoload.php";
require_once "../config/config.php";
use \Firebase\JWT\JWT;

$content = array("name"=>"messi", "age"=>"32");
print json_encode($content);

在Ionic中,最好创建一个ServiceProvider来处理HTTP请求。以下是Ionic 3中的HTTP请求:

FunctionToHandleRequest(){

  let data=JSON.stringify(
    {
    email:this.email,
    password:this.password,
   }
  );
  console.log(data);
  this.http.post("http://localhost/RestLoginWithJwt/server/LoginAuthentication.php",
  data).map(res => res.json())
  .subscribe(data => {
   console.log(data.name);
});
  }

就像我之前所说的,这个在本地测试过了,你可以看到它运行得很好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接