2016-02-16 20 views
0
var users = m.request({ 
    method: "GET", 
    url: "hoge.json", 
    unwrapSuccess: function(response) { 

    return response; 
    }, 
    unwrapError: function(response) { 
    //return response.error; 
    return "404 error"; 
    } 
}); 

users.then(function(result) { 
    console.log(result); 
}); 

刪除「hoge.json」後。如何檢查unwrapError

我想趕上 「404錯誤」,但

uncaught SyntaxError: Unexpected token <


2016年2月18日加

我想測試警報( 「unwrapError」);下面的代碼始終是alert(「unwrapSuccess」);

如何更改以下代碼?

什麼是unwrapError?

▼JS

var users = m.request({ 
    method: "GET", 
    url: "hoge.json", 
    unwrapSuccess: function(response) { 
      alert ("unwrapSuccess"); 
      return response; 
    }, 
    unwrapError: function(response) { 
      alert ("unwrapError"); 
      return "error"; 
    } 
}); 


users.then(function(result) { 
    console.log(result); 
}); 

▼hoge.json

[{"name": "John"}, {"name": "Mary"}] 
+0

您是否檢查過JSON文件格式正確且沒有錯誤?你可以使用http://jsonlint.com/ – Vier

+0

json是否需要正確? 404錯誤是關閉的主題?任何情況下都會變成unwrapError? – user3474300

+0

是的,JSON需要格式正確,我說的是未捕獲的語法錯誤消息可能意味着錯誤是在JSON端,也許如果你添加hoge.json文件,它會更容易告訴我 – Vier

回答

0

如果你看一看mithril's source code你會看到m.request只是爲XMLHttpRequest API的包裝。那就是當請求的readyState屬性更改時會發生什麼:

xhr.onreadystatechange = function() { 
    if (xhr.readyState === 4) { 
     if (xhr.status >= 200 && xhr.status < 300) { 
      options.onload({type: "load", target: xhr}) 
     } else { 
      options.onerror({type: "error", target: xhr}) 
     } 
    } 
} 

所以每當響應狀態不是一個2xx祕銀的unwrapError回調將被調用。

I updated the fiddle calling a URL that returns a 500 response現在調用unwrapError

+0

謝謝!這就是我想知道我的答案。 – user3474300