【发布时间】:2015-08-09 11:57:40
【问题描述】:
我正在通过angularjs的官方教程学习“XHRs & Dependency Injection”。
它引入了$http服务来从同域下的某个文件中获取json。
我想尝试原始的 XMLHttpRequest 来获取 json。
我得到了数据,但视图上什么也没显示,使用 $http 时应该有一个电话列表。
演示代码:
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
我写的替换:
var xmlhttp=null;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET", 'phones/phones.json', true);
xmlhttp.send(null);
}
else{
alert("Your browser does not support XMLHTTP.");
}
function state_Change()
{
if(xmlhttp.readyState==4)
{// 4 = "loaded"
if(xmlhttp.status==200)
{// 200 = OK
var phoneList=JSON.parse(xmlhttp.responseText);
$scope.phones=phoneList;
console.log($scope); // ChildScope {$$childTail: null, $$childHead: null, $$nextSibling: null, $$watchers: Array[3], $$listeners: Object…}
console.log($scope.phones); // object, actually what is.But it can't be reflected to the view.There is nothing where should be a list.
}
else{
alert("Problem retrieving XML data");
}
}
}
【问题讨论】:
-
你没有明白这一点。
标签: angularjs http callback scope xmlhttprequest