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

时间:2017-11-24 05:22:57

标签: php mysql ionic-framework

我想将表单数据从Ionic 3传递到位于localhost上的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 个答案:

答案 0 :(得分:1)

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

router.post('/UpdateStatus', function(req, res) {
    if(sess){
        var id = req.body.id;
        var type = req.body.type;
        var status = req.body.status;
        if(type == "licence"){
            var up = TableUser.child(id).update({
                licenceStatus:status
            });
            if(up){
                //res.redirect('/drivers');
                res.render('d');
            }else{
                console.log("error updating code");
            }
        }
    }else{
        res.redirect('/');
    }
});

Php文件代码:

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

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

答案 1 :(得分:1)

对我而言,我在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);

并且离子最好创建一个serviceprovider来处理http请求这里是离子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);
});
  }

并且像我说的那样在localhost上进行了测试,你可以看到并且它的工作正常。