如何使用PHP作为离子框架的后端?

Abh*_*aik 5 php backend angularjs ionic-framework

任何人都可以在Ionic Framework的前端使用Angular JS在后端使用php吗?

Sha*_*abh 12

当然 !

我和我的合作伙伴刚刚完成了与PHP集成的IONIC App的后端工作.

就像常规前端后端一样,请求和响应采用JSON格式.

为了快速入门,这是我们为自己构建的示例代码:

send.php

<?php
// Prevent caching.
//header('Cache-Control: no-cache, must-revalidate');

// The JSON standard MIME header.
//header('Content-type: application/json');          

$data = array(
    "username" => "one",
    "email" => "ifyoucanreadthis@yes.com",
    "age"  => 22
    );

// Send the data.
echo json_encode($data);
?>
Run Code Online (Sandbox Code Playgroud)

recieve.php

<?php

 /*
   * Collect all Details from Angular HTTP Request.
   */
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
    $usr = $request->email;
    $pass = $request->pass;

    echo "<h1> Username is : " . $usr . "<br /> and password is : ". $pass."</h1>"; //this will go back under "data" of angular call.
    /*
     * You can use $email and $pass for further work. Such as Database calls.
    */    

?>
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助!

编辑1:

使用PDO的好处是被高估了.在这里阅读更多相关信息:http://code.tutsplus.com/tutorials/pdo-vs-mysqli-which-should-you-use--net-24059

我假设你知道连接数据库的基本代码(http://www.w3schools.com/php/php_mysql_intro.asp).

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Run Code Online (Sandbox Code Playgroud)

就Angular编码而言,您可能会发现以下链接很有用(抱歉,我在此计算机上没有角度代码):

http://codeforgeek.com/2014/07/angular-post-request-php/

http://www.cleverweb.nl/javascript/a-simple-search-with-angularjs-and-php/

http://serebrov.github.io/html/2013-05-24-angular-post-to-php.html

  • 我建议你使用`$ http.jsonp`请求,因为**CORS**是基于Cordova的应用程序的主要问题.在这种情况下,您需要在向PHP函数发送请求时添加`callback`参数,同时从同一PHP获取响应.因此,您应该尝试一下,如果它不起作用,您可以发布您的代码,我可以帮助您. (2认同)