如何使用AngularJS的几个ajax调用($ http)来从单个php文件中请求数据?

时间:2016-11-07 22:59:09

标签: javascript php angularjs ajax

我试图使用几个AngularJS的ajax调用来调用单个php文件来相应地获取不同的json数据,下面是我的代码:



var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $http) {
    $http.get('myphp.php',{key: "main1"}).then(function (response){
      console.log(response);
      //do something
    });
    $http.get('myphp.php',{key: "main2"}).then(function (response){
      //do something
    });
 });

<html ng-app="myApp">
<header>
	<!-- AngularJS-->
	<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</header>
<body>
    <div ng-controller="MyController">
      <div id="main1">
        </div>
      <div id="main2">
        </div>
    </div>
</body>
</html>
&#13;
&#13;
&#13;

在myphp.php文件中我有:

&#13;
&#13;
<?php
if (isset($_GET["key"])) {
    if ($_GET["key"]=="main1") {
    	$url1 = 'http://www.w3schools.com/angular/customers.php';
    	$content = file_get_contents($url1);
    	echo $content;
    }
    else if ($_GET["key"]=="main2") {
    	$url2 = "blabla"
    	$content2 = file_get_contents($url2);
    	echo $content2;
    }
}
?>
&#13;
&#13;
&#13;

正如你所看到的,我试图区分不同的ajax调用,并尝试通过在调用myphp.php时发送一个值来从php获取对应的ajax调用中的正确数据。

问题是,,,,它不会起作用,我猜测我的语法搞砸了,你们可以帮忙吗?非常感谢你!

这是我得到的结果: enter image description here

我添加&#34; var_dump($ _ GET);&#34;在我的PHP代码的顶部,这是我得到的。 enter image description here

2 个答案:

答案 0 :(得分:1)

你在html和角度逻辑方面有一些错误。

在html中,您在加载角度核心

之前声明了ng-app指令
 <html >
<header>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
</header>
<body ng-app="myApp">
    <div ng-controller="MyController">
      <button ng-click="getContent('main1')"> main1</button>
      <button ng-click="getContent('main2')"> main2</button>
      <pre>{{content | json}}</pre>
    </div>
</body>
</html>

我们已经在php中看到了逻辑错误:)

<?php
if (isset($_GET["key"])) {
    if ($_GET["key"]=="main1")
        $url = 'http://www.w3schools.com/angular/customers.php';
    else if ($_GET["key"]=="main2")  
        $url = "https://www.google.com";

    $content = file_get_contents($url);
        echo $content;
}
?>

以角度为单位,在没有正确参数的情况下调用两次$http服务。

var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $http) {


    $scope.getContent = function(key){
        $http.get('myphp.php',{params: {key: key}}).then(function (response){
        $scope.content = response.data;
    });
    }
 });

答案 1 :(得分:0)

没关系,我解决了。语法错误,应该是

$http.get(url, {
    params: { param1: value1, param2:value2, param3:value3...... }
});

请参考: http://tutorialsplane.com/angularjs-pass-data-to-http-get-request/