Angularjs - 使用 $http 获取 xml 响应而不是 json

Angularjs - using $http to obtain xml response rather than json

本文关键字:响应 json xml 获取 使用 http Angularjs      更新时间:2023-09-26

我正在尝试使用angularjs/javascript抓取网站。

我知道angularjs提供了一个$http对象,我可以用它来发出get请求。我以前用这个来获取 json,我可以使用相同的对象来获取 XML (HTML) 吗?(我相信响应将使用 gzip 进行编码)。

谢谢!

获取包含 $httpProvider 的 xml 文件不会以 DOM 的形式将响应数据传递到回调中。

使用下面的示例作为模式,并使用旧 IE 客户端中的DOMParser或适当的 ActiveX 对象转换返回的文本。

exampleModule = angular.module('exampleModule', []);
exampleController = exampleModule.controller('exampleController', ['$scope', '$http', function ($scope, $http) {
    $http.get("example.xml").then(function (response) {
        var dom;
        if (typeof DOMParser != "undefined") {
            var parser = new DOMParser();
            dom = parser.parseFromString(response.data, "text/xml");
        }
        else {
            var doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = false;
            dom = doc.loadXML(response.data);
        }
        // Now response is a DOMDocument with childNodes etc.
        return dom;
    });
}]);

您应该能够使用 $http 来获取 JSON 以外的响应数据。 $http文档说明默认响应转换之一是 If JSON response is detected, deserialize it using a JSON parser 。 但是,如果您请求其他内容(例如 HTML 模板),response.data应该具有该 HTML 的字符串值。 事实上,Angular 使用$http来下拉 HTML 以用于ngInclude等。

gzip(或在这种情况下解压缩)应该在响应到达$http之前由浏览器处理。