我从服务器获取json对象。如果json对象的状态为“重定向”,则我正在调用一个函数以重新加载页面的一小部分,然后重定向到包含可重定向到的链接的jsonObject数据值。

$.ajax({
    url: loadUrl,
    dataType: "text json",
    success: function( jsonObject, status ) {

        if ( jsonObject.status == "redirect" ) {

            ajaxLoad($('.list'), $('.group').data('ajax-link'));

            location.href = jsonObject.data;

            return false;
        }

        …


这就是我正在调用的ajaxLoad()函数,它只是重新加载页面的特定部分。

function ajaxLoad(targetBox, loadUrl) {

    $.ajax({
        url: loadUrl,
        dataType: "html",
        timeout: 5000,
        cache: false,
        success: function( html, status ) {
            targetBox.html(html);
                    console.log("function() ajaxLoad : " + status);
        },
        error: function( request, status ) {
            console.log("function() ajaxLoad : " + status);
        }
    });
}


奇怪的是,如果我注释掉location.href = jsonObject.data行,ajaxLoad()函数将记录成功,如果我离开重定向行,则ajaxLoad()函数将记录错误。因此,如果我离开该行,那么ajaxLoad函数将不起作用,如果我删除它,它将起作用。

但是,此行与其余脚本有什么关系?

有任何想法吗?

最佳答案

要重定向,您想使用window.location = jsonObject.data;

我建议将重定向放在您提供给ajaxLoad的回调中,这样重定向将在THAT ajax调用成功时发生。那不会是一场比赛。

// Call ajaxLoad with the callback
ajaxLoad($('.list'), $('.group').data('ajax-link'), function(){window.location = jsonObject.data;});

// Add the callback to ajaxLoad
function ajaxLoad(targetBox, loadUrl, callback) {

    $.ajax({
        url: loadUrl,
        dataType: "html",
        timeout: 5000,
        cache: false,
        success: function( html, status ) {
            targetBox.html(html);
                    console.log("function() ajaxLoad : " + status);

            if(typeof(callback) == 'function')
            {
                // Execute the redirect here
                callback();
            }
        },
        error: function( request, status ) {
            console.log("function() ajaxLoad : " + status);
        }
    });
}

关于javascript - jQuery Ajax:使用json重定向-无法解释的行为?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7053783/

10-11 22:47
查看更多