【发布时间】:2025-09-01 10:00:02
【问题描述】:
我正在使用 ionic 2 开发一个混合应用程序,我必须将数据从服务器(PHP 文件)传递到 ionic 应用程序。 我知道我必须使用 HTTP 请求在服务器和应用程序之间传递数据,我在网上搜索并找到了一个适合我的代码示例,但问题是此代码使用函数“echo”,我会将变量的值传递给应用程序和之后,因为我需要修改它。
这是代码:
离子应用程序中的表单:
<ion-content padding="true">
<form ng-submit="submit()">
<label class="item item-input item-stacked-label">
<span class="input-label">username</span>
<input type="text" name="username" placeholder="enter username" ng-model="data.username">
</label>
<input class="button button-block button-positive" type="submit" name="submit" value="Submit to server">
</form>
<div class="card">
<div class="item item-text-wrap">
Response: <b ng-bind="response"></b>
</div>
</div>
</ion-content>
app.js 中的控制器:
.controller('AppCtrl', function($scope, $http) {
$scope.data = {};
$scope.submit = function(){
var link = 'http://localhost/ShuttleFIX/api.php';
$http.post(link, {username : $scope.data.username}).then(function (res){
$scope.response = res.data;
});
};
});
服务器上的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
}
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);
$username = $request->username;
if ($username != "") {
echo "Server returns: " . $username;
}
else {
echo "Empty username parameter!";
}
}
else {
echo "Not called properly with username parameter!";
}
有人可以帮我吗?
谢谢
【问题讨论】:
-
不清楚你想要什么..使用json发送和接收数据..解释一下..
标签: javascript php ionic-framework httprequest ionic2