如何捕获服务器错误JS

时间:2015-03-09 22:41:51

标签: javascript jquery json callback iteration

我正在学习JavaScript,通过反复试验,有时服务器没有响应,并在内部生成Internal Server Error (500),并且随着错误的累积,您开始滞后于页面。

也许我以错误的方式组装代码?或者我的功能混合不好?

即使我用try/catch发现500错误,并试图调用函数update但我无法抓住他。

有时JSON会出现null,并发送错误。 我能抓住这个错误吗?

这是代码。

jsfiddle.net/rocr/pa0221k6/

    var width = $('.ticker-text').width(),
    containerwidth = $('.ticker-container').width(),
    left = containerwidth;
    var timer;
$(document).ready(function(e){

//timer
function Timer(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };

    this.resume = function() {
        start = new Date();
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
    };

    this.resume();
}


//show stock quotes    
function update() {
    var query = "select * from yahoo.finance.quotes where symbol = ";
    var symbolo = "'aapl'"; 
    var yql = "http://query.yahooapis.com/v1/public/yql?q=" + escape(query+symbolo) + "&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback=?";
    var xhr2 = $.ajax({ 
        url: yql,
        jsonp: "myCallback",
        dataType: 'json', 
        success: function(data) {
            var keys = data.query.results.quote;
            $("#a").html(keys.LastTradePriceOnly);
            $("#b").html(keys.LastTradePriceOnly);
            update();
        }, 
        error: function(xhr, ajaxOptions, thrownError) {
            //console.log(xhr.status + " , " +thrownError);
            //console.log('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
            update();
        },
        statusCode: {
            500: function() {
                console.log( "Error 500" );
                alert( "Error 500" );
                update();
            }
        },
        timeout: 3000
    });

}


//move div    
function tick() {
        if(--left < -width){
            left = containerwidth;
        }
        $(".ticker-text").css("margin-left", left + "px");
        //setTimeout(tick, 16);
        timer = new Timer(tick, 16);
      }
      tick();
      update();

        $("#b").hover(function(){
        timer.pause();
        $("#b").css("background-color", "yellow");
        },function(){
        timer.resume();
        $("#b").css("background-color", "pink");
        });

});

1 个答案:

答案 0 :(得分:0)

如果没有处理ajax请求,请尝试再次处理DOM中的显示。

success: function(data) {
  try{
    var keys = data.query.results.quote;
    var keys = data.query.results.quote;
    $("#a").html(keys.LastTradePriceOnly);
    $("#b").html(keys.LastTradePriceOnly);
    update();
  }
}