我有一个想要读入对象的模拟json文件。我的代码如下所示:
m = require('mithril');
/* .. snip .. */
var foo = m.prop([]);
m.request({
method: 'GET',
url: './foo.json',
unwrapSuccess: function (a, b) {
console.log("success");
},
unwrapError: function (a, b) {
console.log("error");
}
}).then(function (a) {
// fill in foo
console.log("object filled");
});
代码始终只会点击unwrapError
挂钩。
令我困惑的是这两件事:
与documentation相反,响应对象不包含“错误”属性,告诉我发生了什么。
我做错了什么?
答案 0 :(得分:2)
我做了一个示例,展示了如何使用unwrapSuccess/unwrapError
:
// No need for m.prop since m.request returns a GetterSetter too
var foo = m.request({
method: 'GET',
url: '//api.ipify.org?format=json',
unwrapSuccess: function (a, b) {
console.log("success: " + a.ip);
// Remember to return the value that should be unwrapped
return a.ip;
},
unwrapError: function (a, b) {
console.log("error");
}
}).then(function (ip) {
console.log("object almost filled");
// And remember to return the value to the GetterSetter
return ip;
});
m.mount(document.getElementById('content'), {
view: function() { return "Your IP: " + foo(); }
});
在此测试:http://jsfiddle.net/ciscoheat/LL41sy9L/
编辑:实际问题是本地文件正在发出ajax请求。 Chrome不允许来自file://
网址的Ajax来电。使用像http-server这样的简单Web服务器来处理Node.js将解决这个问题。