gpt4 book ai didi

javascript - 如何在 angular.js 中使用 $http 创建同步?

转载 作者:行者123 更新时间:2023-11-28 19:33:34 24 4
gpt4 key购买 nike

我是java脚本的初学者,不明白如何使用$http对象创建同步Ajax调用,如果有人有想法请指导我,我如何通过$http同步进行Ajax调用

我的代码如下 -

var AjaxModule = angular.module('AjaxModule',[]);
AjaxModule.controller('AjaxController',function($scope,$http){
var path ="http://localhost/services_ajax/";
var serviceName = 'customers';
var response = $http.get(path+serviceName);
response.success(function(data){
$scope.list = data;
});
});

最佳答案

您无法使用 $http 服务发出同步请求。它在服务代码中被硬编码为异步。但是,您可以创建自己的同步服务。

var myApp = angular.module('myApp', []);

myApp.service('synchronousService', [function () {
var serviceMethod = function (url) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Your browser don't support XMLHttpRequest");
}

request.open('GET', url, false);
request.send(null);

if (request.status === 200) {
return request.responseText;
}
};
return serviceMethod;
}]);

myApp.controller('AppCtrl', function ($scope, synchronousService) {
var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22AAPL%22%29&env=store://datatables.org/alltableswithkeys";
alert(synchronousService(url));
});

这是正在运行的 jsfiddle: http://jsfiddle.net/zono/uL0e1j3e/18/

只是说同步请求是一个非常糟糕的主意。

关于javascript - 如何在 angular.js 中使用 $http 创建同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26318063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com