2016-12-05 52 views
1

我必須將xml response to json轉換爲angularjs。我使用的是一個Rest api,它以xml格式提供響應,但是當通過$ http.get()獲取時,angularjs需要json響應。使用angularjs從數據庫檢索記錄後,將xml轉換爲json

以下是我如何在angularjs中使用rest api。

<script> 
var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope,$http) { 

$http({ 
method: 'GET', 
url: "https://some-url?fieldList=field1,field2" 
}).then(function(response) { 
     $scope.obj=response.data.records;},function(response){});} 
}); 
</scripts> 

如何將xml響應轉換爲json並將其作爲輸入提供給某個變量$ scope.obj?

回答

0

這裏是你如何能做到這一點, 我用這個頁面https://davidwalsh.name/convert-xml-json

var xhttp = new XMLHttpRequest(); 
xhttp.onreadystatechange = function() { 
if (this.readyState == 4 && this.status == 200) { 
    myFunction(this); 
} 
}; 
xhttp.open("GET", "your.xml", true); 
xhttp.send(); 

function myFunction(xml) { 
var xmlDoc = xml.responseXML; 
document.getElementById("demo").innerHTML = 
xmlToJson(xmlDoc); 
} 
function xmlToJson(xml) { 

// Create the return object 
var obj = {}; 

if (xml.nodeType == 1) { // element 
    // do attributes 
    if (xml.attributes.length > 0) { 
    obj["@attributes"] = {}; 
     for (var j = 0; j < xml.attributes.length; j++) { 
      var attribute = xml.attributes.item(j); 
      obj["@attributes"][attribute.nodeName] = attribute.nodeValue; 
     } 
    } 
} else if (xml.nodeType == 3) { // text 
    obj = xml.nodeValue; 
} 

// do children 
if (xml.hasChildNodes()) { 
    for(var i = 0; i < xml.childNodes.length; i++) { 
     var item = xml.childNodes.item(i); 
     var nodeName = item.nodeName; 
     if (typeof(obj[nodeName]) == "undefined") { 
      obj[nodeName] = xmlToJson(item); 
     } else { 
      if (typeof(obj[nodeName].push) == "undefined") { 
       var old = obj[nodeName]; 
       obj[nodeName] = []; 
       obj[nodeName].push(old); 
      } 
      obj[nodeName].push(xmlToJson(item)); 
     } 
    } 
} 
return obj; 
}; 
上給出的函數