2016-05-05 17 views
0

當表單成功提交時,如何讓頁面重定向?使用PHP重定向進行Ajax調用

當前當表單提交時出現錯誤,錯誤出現在表單上方。

當表單提交時沒有錯誤,成功頁面顯示在窗體上方的錯誤消息容器中(而不是重定向)。

我的Ajax:

function checkform() { 

var form = $('form')[0]; 
var data = new FormData(form); 

    $.ajax({ 
     url: 'upload.php', 
     data: data , 
     processData: false, 
     contentType: false, 
     dataType: 'text', 
     cache: false, 
     type: 'POST', 
     success: function(data){ 
     $("div#error").html(data).slideDown("fast"); 

     //Scroll to top of this div - 70px from the top of your view, change this to whatever number you wish 
     var destination = $('div#uploadContainer').offset().top - 15; 
     $("html:not(:animated),body:not(:animated)").animate({ 
      scrollTop: destination 
     }, 200); 
     } 
    }); 
    return false; 
} 

我的PHP(後驗證等...)你需要重定向頁面在JavaScript success功能

if (isset($_POST['messageSubmit'])) { 
    header('Location: ' . $message_location); 
} 

if (isset($_POST['drawingSubmit'])) { 
    header('Location: ' . $drawing_location); 
} 

if (isset($_POST['postSubmit'])) { 
    header('Location: ' . $other_location); 
} 
+1

你應該在成功響應中寫入位置 –

+0

如果您試圖在成功回調中獲取標頭,則需要使用* jqXHR * object:'jqXHR.getResponseHeader('Location')' – Hkan

+0

如何指定要在哪個重定向中使用Ajax雖然?在PHP中,重定向取決於點擊哪個提交按鈕。 – DavidPottrell

回答

0

,是與window.location.href = "http://yourNewLocation"完成。在你的情況下,我會用onSubmit = "return false"替代onSubmit = "checkForm()",在你的輸入中你可以添加<input type="submit" name="drawingSubmit" value="Upload now" onClick = "checkForm('drawingSubmit')" />。現在,在您的checkForm()功能,您可以獲取點擊input作爲參數的名字 - '

function checkForm(inputName){ 
    //current code 
     if(inputName == "drawingSubmit"){ 
      window.location.href = "//wherever you want to redirect the user"; 
     } 
    } 
+0

我將如何聲明在Ajax中使用哪個重定向?在PHP中,重定向取決於點擊哪個提交按鈕。 – DavidPottrell

+0

當你調用'checkForm'時,你可以給它傳遞一個帶有按鈕名稱的參數。取決於你當前的代碼,你可以使用'.on('click',function(){...'事件,或者你可以在代碼中傳遞參數,如果你有內聯'onclick'函數''onclick = checkForm(「 messageSubmit「)' –

+0

有沒有可用於這樣的資源?我不明白。 – DavidPottrell

0

success回調函數必須設置窗口位置href的:

window.location.href = 'http://example.com/your-new-path'