[英]How to replace ajax call with $http, AngularJs
I am trying to implement angular.js in my php file, Because it's only one file project, So I am thinking where I use AngularJS. 我试图在我的php文件中实现angular.js,因为它只是一个文件项目,所以我在考虑在哪里使用AngularJS。 So i decided to replace AJAX call with $http
. 所以我决定用$http
代替AJAX调用。
For this i imported google angular js file 为此,我导入了谷歌角度js文件
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
And replace my this ajax call 并替换我的这个ajax电话
$.ajax({
url: url,
type: "GET",
data: data,
async: false,
success: function(res) {
resData = res;
}
});
With 用
$http({
url: url,
method: "GET",
data: data
}).success(function(data, status, headers, config) {
resData = data;
}).error(function(data, status, headers, config) {
resData = data;
});
beside these nothing changed, but when i am trying to execute my code, I am getting this error 除了这些以外,什么都没有改变,但是当我尝试执行我的代码时,我得到了这个错误
$http is not defined $ http未定义
In order to use $http you first need to inject it into your controller 为了使用$ http,首先需要将其注入到控制器中
var module = angular.module('putNameHere', [])
module.controller('myCtrl', ['$http', function($http){ //injection here
$http({
url: url,
method: "GET",
data: data
}).success(function(data, status, headers, config) {
resData = data;
}).error(function(data, status, headers, config) {
resData = data;
});
}])
You are going to have to actually load an angular module and controller, then inject $http into the controller: 您将必须实际加载一个角度模块和控制器,然后将$ http注入到控制器中:
<script>
var app = angular.module('app', []);
app.controller('HttpCtrl', function($http) { //this is the $http injection here
//insert your $http code here
})
</script>
Plunker Demo (change google.com to whatever url you need to use) Plunker演示 (将google.com更改为您需要使用的任何网址)
You will also need to add the ng-app='app' attribute to your <html>
tag, and the ng-controller='HttpCtrl' attribute to your <body>
tag. 您还需要将ng-app ='app'属性添加到<html>
标签,并将ng-controller ='HttpCtrl'属性添加到<body>
标签。
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error. $ http服务是一个带有单个参数(配置对象)的函数,该参数用于生成HTTP请求,并使用两个$ http特定方法返回成功的诺言:成功和错误。
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
source https://docs.angularjs.org/api/ng/service/ $http 来源https://docs.angularjs.org/api/ng/service/ $ http
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.