我有以下 JavaScript
patients.prototype.GetPatient = function(patient_id,callback)
{
var xmlhttp;
var fullpath;
try {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var pat = parseJson(xmlhttp.response);
if (pat) {
callback(parseJson(xmlhttp.response));
}
else {
alert('Null object returned?');
}
}
else if (xmlhttp.status == 404) {
alert('Unable to find Retrieve Patient Service');
}
}
xmlhttp.open("GET", "RetrievePatient.ashx?PatientId=" + patient_id, true);
xmlhttp.send();
}
catch (e) {
alert('Unable to retrieve requested patient details');
}
}
function parseJson(jsonString) {
var res;
try {
alert('Parsing JSON');
res = JSON.parse(jsonString);
}
catch (e) {
alert('Call to evaluate result failed with error ' + e.message + ' Evaluating Json ' + jsonString );
};
return res;
}
如果这是从 IE10 上运行的页面运行的,我会正确返回患者详细信息。如果我在 Chrome 上运行它,它会返回患者的详细信息,但如果我在 IE8 的页面上运行它,JSON 将为 null,整个事情就会崩溃。
有人知道我可以做些什么来使其在 IE8 中运行吗?
最佳答案
在尝试解析之前尝试检查是否为 null。另外,添加对未定义的检查
function parseJson(jsonString) {
var res;
if (jsonString == undefined) {
return jsonString;
}
if (jsonString == null) {
return jsonString;
}
if (window.JSON && window.JSON.parse ) {
res = JSON.parse(jsonString);
return res;
}
}
关于javascript - 从 http 处理程序返回的 JSON 在 IE8 中为 null,但在 IE10 或 Chrome 中则不然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27905762/