javascript - 从 http 处理程序返回的 JSON 在 IE8 中为 null,但在 IE10 或 Chrome 中则不然

标签 javascript json internet-explorer internet-explorer-8

我有以下 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/

相关文章:

javascript - 访问默认的 OpenLayers 样式

javascript - 如何使用 actions 在 React es6 和 axios 中发布数据

python - django-rest-framework:如何序列化已包含 JSON 的字段?

java - Gson -> 导入带有对象的 JSON

javascript - Opera 和 Internet Explorer 中的 JQuery 安全错误

javascript - 是否可以更改 :before using javascript or jQuery

javascript - 如何在 Flow 中用多个可能的调用签名来注释一个函数?

json - REST:使用一个请求更新多个资源 - 它是标准的还是应该避免的?

javascript - Web worker 文件被缓存并且永远不会在 IE 11 中重新加载

html - CSS 在本地服务器上的呈现方式与在 IE 中通过互联网呈现的方式不同