winjs.xhr是windows store app中封装xmlhttpwebrequest的一个promise object,可以cross domain,出于安全不能访问本地和局域网的service。
下面例子是一个使用的demo:
var feedItems = [];
function loadBlogFeedsFromWebAsXML() {
var feedUrl = "http://blogs.msdn.com/b/windowsstore/rss.aspx";
WinJS.xhr({ url: feedUrl }).then(
function (result) {
var xmlDoc = new Windows.Data.Xml.Dom.XmlDocument();
xmlDoc.loadXml(result.responseText);
var nodes = xmlDoc.selectNodes("//item");
var items = new Array();
nodes.forEach(function (val, idx, travObj) {
var title = val.selectSingleNode("title").innerText;
var description = val.selectSingleNode("description").innerText;
var link = val.selectSingleNode("link").innerText;
var newItem = {
title: title,
summary: description,
uri: link
};
items.push(newItem);
});
DataUtils.feedItems = items;
// Call other function which can use the DataUtils.feedItems to bind UI elements
//做想要在winjs.xhr中想做的事情,不要在函数外面去做,这就是异步编程:)
},
function (err) {
}
);
return DataUtils.feedItems;
}
WinJS.Namespace.define(
"DataUtils", {
feedItems: feedItems
}
);
下面demo是向webservice中post json的例子:
function CallData() {
var person = { 'Name': 'Name'};
WinJS.xhr({
type: "POST",
url: "http://www.xxx.com/WebService.asmx/method",
headers: { "Content-type": "application/json" },
data: JSON.stringify(person)
}).then(function complete(request) {
var resdata = request.responseText;
}, function error(er) {
var err = er.statusText;
});
}