因此,我大体上同意,更好的解决方案是确保服务器只返回JSON,不过这是通过客户端Javascript实现的一种快速方法,如@Barmer所建议的那样,将html解析到DOM,获取body中的文本childNode并在其上运行JSONParse。在var responseStr = '' +
'
' +'
503 Service Unavailable' +'' +
'
' +'
503 Service Unavailable
' +'{' +
' "status": "object-specific error",' +
' "payload": {' +
' "Message": "Unable to list resources",' +
' "HTTP Method": "GET",' +
' "URI": "api/myManager/1.0/Node",' +
' "Operation": "LIST",' +
' "Object": {' +
' "Name": "myManager.Node",' +
' "Interface": "Node"' +
' },' +
' "Version": {' +
' "Major": 1,' +
' "Minor": 0' +
' }' +
' }' +
'}
' +
'' +
'';
var parser = new DOMParser();
var doc = parser.parseFromString(responseStr, "text/html");
var items = doc.body.getElementsByTagName("*");
var json_obj;
for (var i = 0, len = doc.body.childNodes.length; i < len; i++) {
if (doc.body.childNodes[i].nodeName == "#text") {
json_obj = JSON.parse(doc.body.childNodes[i].data);
break;
}
}
// You can access json directly now e.g.
console.log(json_obj.status);
console.log(json_obj.payload['HTTP Method']);