从 http 处理程序返回的 JSON 在 IE8 中为空,但在 IE10 或 Chrome 中不是

JSON returned from http handler is null in IE8 but not IE10 or Chrome

本文关键字:但在 IE10 Chrome 返回 程序 处理 JSON IE8 http      更新时间:2023-09-26

>我有以下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 为空,整个事情就会失败。

有人知道我可以做些什么来在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;
   }
}