使用PHP的angularjs,ionic和json解码 [英] angularjs, ionic, and json decode using php

查看:142
本文介绍了使用PHP的angularjs,ionic和json解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ionic框架和AngularJS.我想从Mysql检索数据并使用PHP解码为JSON,以便可以在Ionic App中使用它.

I'm working with Ionic framework and AngularJS. I want to retrieve data from Mysql and decode to JSON using PHP so that I can use it in my Ionic App.

这是我的PHP代码

<?php

/*

Here was my php codes to get all data from mysql and assign it to $episode array

*/

header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

echo json_encode($episode);


//close the db connection
mysqli_close($connection);

当我在浏览器中运行我的应用程序时,控制台显示了此错误

When I run my App in the browser The console gave me this error

XMLHttpRequest cannot load http://***Here Was My Url***/episodes.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

控制器代码

$scope.posts = [];
var Url = "http://here was my url/episodes.php";

$http.get(Url)
.success(function(response){
  console.log("Reveived getPosts via HTTP: ", response, status);
  angular.forEach(response, function(child){
    $scope.posts.push(child);
  });
})
.error(function(response, status){
  console.log("Error while received response. " + status + response);
});

但是当我在真实设备中运行该应用程序时,阵列给了我这个 http://i.imgur.com/lI2ihb9.png

But when I run the App in a real device the array gave me this http://i.imgur.com/lI2ihb9.png

希望您能帮助我解决问题.

Hope you can help me to solve it.

推荐答案

将此添加到您的index.php文件

Add this to your index.php file

// Allow from any origin
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, PUT, DELETE, OPTIONS");         

if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

}

或者,您也可以将其添加到您的.htaccess文件中:

Alternatively you could also add this to your .htaccess file:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

这篇关于使用PHP的angularjs,ionic和json解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆