jQuery中的getJSON方法请求的接口有错误时的处理方法


在用jQuery中的getJSON方法时,通常会碰到请求的接口有错误的情况发生,这时我们可以用下面的方法来做处理,代码如下:

<script type="text/javascript">

        function GetDatas(url) {
            try {
                $.ajaxSetup({
                    error: function (x, e) {
                        $("#content").html("暂无具体内容!");
                        return false;
                    }
                });
           
                $.getJSON(url, function (data) {
                    if (data != null) {
                        $(".TitleStyle").html(data["root"][0]["data"][0]["Title"]);
                        var date = data["root"][0]["data"][0]["Date"];
                        if (date.length == 8) {
                            $("#strDate").html(date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8));
                        }
                        $("#strAuthor").html(data["root"][0]["data"][0]["SecuName"]);
                        $("#content").html(data["root"][0]["data"][0]["Content"]);
                    }
                    else {
                        $("#content").html("暂无具体内容!");
                    }
                });
            }
            catch (ex) {
                $("#content").html("暂无具体内容!");
            }
        }
    </script>

相关内容