我正在尝试使用几个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>
在myphp.php文件中,我有:
<?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;
}
}
?>
如您所见,我正在尝试区分不同的ajax调用,并通过在调用myphp.php时发送值来尝试从php的对应ajax调用中获取正确的数据。
问题是,它不起作用,我猜我的语法搞砸了,你们能帮忙吗?提前非常感谢您!
这是我得到的结果:
我添加“ var_dump($ _ GET);”在我的php代码的顶部,这就是我得到的。
参考方案
您在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;
});
}
});
Telerik单选按钮所需的字段验证器 - javascript如何设置Telerik单选按钮所需的字段验证器?我想在按钮单击“ BtnSave”上设置必填字段验证器吗?请帮忙!<telerik:RadButton ID="radio_male" runat="server" ToggleType="Radio" AutoPostBack="fa…
选择后显示输入元素 - javascript我有一个表格,其中取决于用户的选择,输入元素是否可见。实际上,用户正在以另一种形式设置已定义的合作伙伴类型,并且如果选中该元素,则允许在该类型的合作伙伴上可见的元素类型1将显示以下元素:<input type="text" id="partner" name="partner" class=&…
在PHP文件中调用javascript函数并在加载HTML文件之后? - javascript我需要在我的php中调用js函数,但无法正常工作。有人可以告诉我我在做什么错吗?我该如何轻松地做到这一点?谢谢!我有三个文件: mail.php负责发送$ _POST的内容(工作正常)。我调用我的javascript函数来切换模式,具体取决于邮件是否已发送。 <? ... $response = $sendgrid->send($email);…
在提交时在表单操作中获取变量丢失 - javascript当表单由onchange事件提交时,它不会保留get变量view。任何想法为什么会发生这种情况?提交后,这是它进入的网址,index?month=February&year=2014<form action="index?view=list" class="pure-form pure-fo…
JavaScript将PHP中的字符串和整数传递给函数 - javascript我正在尝试将字符串和整数都传递到同一函数中,但是引号引起了问题。我发现错误出在echo $q->info部分,我必须在此代码上使用双引号。有人可以帮我写这个$q->info,但不能获得真正的价值吗?到目前为止,我的代码是<td><a href="javascript:add(<?php echo $q->i…