Angularjs $http VS jquery $.ajax [英] Angularjs $http VS jquery $.ajax
问题描述
我可以在 Angularjs $http
中设置 context
就像我们可以在 jQuery 的 $.ajax
中一样吗?
define(['应用程序'],功能(应用程序){app.controller("controller1", function($scope, $route, $http) {返回 $http({方法:'获取',网址:'server.php'}).then(函数(响应){$scope.contacts = response.data;});});});
此外,jQuery 的 $.ajax
中还有更多回调,例如 .done
、.promise
,我可以使用它们来操作context
像下面这样,我想知道我是否可以在 Angularjs
中做同样的事情?
$.ajax({类型:获取",数据类型:HTML",网址:'server.php',上下文:$("#container"),异步:真,发送前:函数(){$(this).html('加载中...');},成功:函数(返回数据,状态,jqxhr){$(this).html(returndata).hide().fadeIn();},}).失败(函数(){警报(错误");}).完成(函数(返回数据){},.总是(功能(){警报(完成");}});
两者都一样
$http 引用自 angular.js 脚本
$.ajax 引用自 jquery 脚本
和 $http 不支持
async:false
$.ajax 支持
async:false
你可以通过这种方式使用angular.js
$http.get('server.php').success(function(response) {$scope.contacts = response.data;}).错误(函数(错误){//一些代码});
但是 async: true,
在 angular.js
中不受支持.
如果需要停止异步回调,则必须使用$.ajax
方式
更多细节请看这个讨论:从 jquery $.ajax 到 angular $http
如何在angular js
xx$http.get('server.php').success(function(response) {$scope.contacts = response.data;$scope.IsShow=true;$scope.$apply();}).错误(函数(错误){$scope.IsShow=false;$scope.$apply();});
Can I set context
in Angularjs $http
just like we can do it in jQuery's $.ajax
?
define([
'app'
], function(app) {
app.controller("controller1", function($scope, $route, $http) {
return $http({
method: 'GET',
url: 'server.php'
}).then(function(response) {
$scope.contacts = response.data;
});
});
});
Also, there are more callbacks in jQuery's $.ajax
, like .done
, .promise
which I can use them to manipulate the context
like this below, I wonder if I can do the same in Angularjs
?
$.ajax({
type: "GET",
dataType: "HTML",
url: 'server.php',
context: $("#container"),
async: true,
beforeSend: function() {
$(this).html('loading...');
},
success: function (returndata, status, jqxhr) {
$(this).html(returndata).hide().fadeIn();
},
}).fail(function() {
alert("error");
}).done(function(returndata) {
},
.always(function() {
alert("complete");
}
});
Both are same
$http is referred from angular.js script
$.ajax is referred from jquery script
and $http does not support
async:false
$.ajax supports
async:false
You can do it by using angular.js
in this way
$http.get('server.php').success(function(response) {
$scope.contacts = response.data;
}).error(function(error)
{
//some code
});
but async: true,
is not supported in angular.js
.
If you need stop asynchronous callback, then you must use $.ajax
way
More details please see this discussion : from jquery $.ajax to angular $http
Edit:
How to show hide in angular js
<div ng-show="IsShow">xx</div>
$http.get('server.php').success(function(response) {
$scope.contacts = response.data;
$scope.IsShow=true;
$scope.$apply();
}).error(function(error)
{
$scope.IsShow=false;
$scope.$apply();
});
这篇关于Angularjs $http VS jquery $.ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!