1

我有一个要读入对象的模拟 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打钩。

真正让我困惑的是这两件事:

  • 请求成功 - 我可以在 Chrome 的开发工具中看到它。没有任何访问错误的迹象;
  • 错误钩子接收到的第一个参数是我所期望的 JSON;第二个参数是对应的 XMLHttpRequest 对象,没有任何错误指示。

因此,与文档相反,响应对象不包含告诉我发生了什么的“错误”属性。

我究竟做错了什么?

4

1 回答 1

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://URL 的 ajax 调用。为 Node.js使用像http-server这样的简单 Web 服务器将解决这个问题。

于 2015-06-09T10:47:07.680 回答