dongmeiran609914 2014-08-22 19:48
浏览 26

AngularJS从跨域的PHP服务获取数据

I currently have a script that checks my server information. They have provided a file called index.php - when I load this file in the URL, the content of an .xml file is generated.

My question is, how can I get data from this php file/URL in my Controller?

I use the php url in script but its not working.

Controller.js

var Factory = angular.module('Factory ', ['ngRoute']);
Factory .controller('Controller', function ($scope, $http, $route)
{
     $http.get('http://example.com/index.php')
        .success(function (data) {
            $scope.data = data;
        })
        .error(function (data, status) {
            $scope.data = data || "FALSE";
            alert("error");
        });
});    

index.php

<?php
$mysqli = new mysqli('example.com','abc_5','gf#$6','example_db');
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS SP_getName") ||
    !$mysqli->query('CREATE PROCEDURE SP_getName() BEGIN SELECT Name from user_tbl END;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$result = $mysqli->query("CALL SP_getName()");
while($row = mysqli_fetch_assoc($result)) {
    $output[] = array_map('utf8_encode', $row);
}
print(json_encode($output));
?>

I try to call the data from the service, I get nothing. I understand that the query is asynchronous but I am having a hard time understanding how to populate the $scope variable once the data is returned.

  • 写回答

1条回答 默认 最新

  • dongtao4319 2014-08-22 20:08
    关注

    Possibly you have to add the following to your headers in PHP:

    <?php header("Access-Control-Allow-Origin: *"); ?>
    

    More information can be found here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大