2012-01-31 25 views
2

我想創建一個可以處理表單的彈出框(帶有jQuery),並且在大部分情況下,我都可以使用它。我唯一的問題是,在成功登錄和/或註冊時,PHP會發送一個標題位置以將用戶重定向到他們的「主目錄」,並且它會創建一個無限循環的重定向,並在div中加載該表單。

如果在發佈請求中發送了location標題,然後獲取作爲新發布的location發送的實際URL,我該如何去閱讀?

這是我到目前爲止已經試過(除其他事項外):

$('.register').live('submit', function(e) { 

    e.preventDefault(); 

    var form_data = $(this).serialize() + '&register=register&js=true'; 

    $.post(site_path + '/register', form_data, function(data, text, xhr) { 

     alert(xhr.getResponseHeader("Location")); 

     // $('.overlay_container').html(data); 

    }); 

}); 

不知道究竟我做錯了,但據我所知,類似的規定應該工作。我也試着用普通的AJAX post請求來做到這一點,但沒有得到預期的結果。

只要注意,那裏不會總是一個位置標題發送;只有當一個人成功登錄,寄存器等

理想的情況下,這就是我要完成的:

$('.register').live('submit', function(e) { 

    e.preventDefault(); 

    var form_data = $(this).serialize() + '&register=register&js=true'; 

    $.post(site_path + '/register', form_data, function(data, text, xhr) { 

     var header_location = xhr.getResponseHeader("Location"); 

     if(header_location == null) { 

      $('.overlay_container').html(data); 

     }else{ 

      window.location = header_location; 

     } 

    }); 

}); 
+1

您應該避免使用'jQuery.live()'在任何時候!使用'.on()'。如果'.on()'在您的jQuery版本中不可用,請使用'.delegate()'。 – Tadeck 2012-01-31 22:57:01

+0

@Tadeck最初我曾嘗試使用'.on()',但它似乎不起作用。我正在使用Google CDN的1.7.1版本。據我所知,它應該包含在那裏(從1.7開始),但它沒有奏效。 http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js – 2012-01-31 23:02:28

+0

'.on()** **自1.7以來包含**,它絕對有效。此外,'.on()'可以完全替代'.live()'和'.delegate()',它們優於它們,並且意味着替換它們。看來你使用不正確,或者你犯了一些其他錯誤。 – Tadeck 2012-01-31 23:14:35

回答

1

就一個,我知道,你不能真正讀取Location頭,如JavaScript直到他們停下來,然後發回headers,這意味着我得到目標頁面的標題,而不是最初發布到的頁面。

因此,如果使用JavaScript(或jQuery)請求頁面,我編輯了我的PHP腳本中的重定向函數以發送自定義頁眉。

public function redirect($redirect = NULL) { 

    global $_CONFIG; 

    if($_POST['js'] == 'true') { 

     exit(header('Redirect: ' . $_CONFIG['site']['path'] . '/' . $redirect)); 

    }else{ 

     exit(header('Location: ' . $_CONFIG['site']['path'] . '/' . $redirect)); 

    } 

} 

這樣我就可以讀取重定向是否實際發送,並在JavaScript(jQuery)結束時正確處理它。

這裏是最後的結果是什麼樣子:

$('.popup').on('submit', '.register', function(e) { 

    e.preventDefault(); 

    var action = $(this).attr('action'), form_data = $(this).serialize() + '&register=register&js=true'; 

    $.post(action, form_data, function(data, text, xhr) { 

     var header_location = xhr.getResponseHeader('Redirect'); 

     if(header_location == null) { 

      $('.overlay_container').html(data); 

     }else{ 

      window.location = header_location; 

     } 

    }); 

}); 
+1

根據我的經驗,情況並非如此,具有位置標頭的任何東西都會被瀏覽器自動跟蹤。我只是做了一個測試,並收到了第一級的迴應。 – 2013-06-29 18:24:55