首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将表单数据从Ionic 3传递到PHP文件?

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

Stack Overflow用户
提问于 2017-11-24 13:22:57
回答 2查看 2.8K关注 0票数 3

我想将表单数据从Ionic 3传递到位于localhost上的php文件。下面是我的离子按钮代码:

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

请检查代码,如果有任何错误,请告诉我。我想传递数据从离子到Php文件,然后mysql数据库。我已经成功地在php和mysql数据库之间建立了连接,但是我无法将数据从Ionic表单传递到php,尽管它没有显示任何错误。提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-11-24 14:41:10

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

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!";
    }
 ?>   

如果有人想要,你可以参考代码...:)

票数 2
EN

Stack Overflow用户

发布于 2018-06-19 06:58:06

嗯,对我来说,我在localhost上测试的最简单的方法是...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);
});
  }

正如我所说的,这是在本地主机上测试的,正如你所看到的,它工作得很好。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47466814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档