2016-05-05 44 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'