【问题标题】:Angularjs - using $http to obtain xml response rather than jsonAngularjs - 使用 $http 获取 xml 响应而不是 json
【发布时间】:2013-10-28 19:14:01
【问题描述】:

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

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

谢谢!

【问题讨论】:

    标签: javascript html xml angularjs


    【解决方案1】:

    使用 $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;
        });
    }]);

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 如果您期望 success 回调中传递的参数是来自本地 XMLHttpRequestresponseXML 属性,基于响应标头中的文件扩展名或 MIME,它不是t.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      相关资源
      最近更新 更多