通过Ajax时,标头不会重定向 [英] Header wont redirect when passedthrough ajax
问题描述
不确定是否可行,但是我有一个页面使用AJAX提交表单,如果满足某些条件,它将自动将用户带到另一个页面.在标题标记之前,仅输出一堆条件就输出NOTHING.
Not sure if this is possible but I have a page that submits a form with AJAX and if it meets certain conditions it should automatically take the user to another page. NOTHING is outputted before the header tag its just a bunch of conditions.
问题:标题重定向不起作用...
Problem: Header redirect not working...
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
header("Location: http://localhost/manage/card.php?id=$id");
推荐答案
您在问题中指出,在某些条件下,您需要重定向.
You indicate in the question that under certain conditions, you want a redirect.
为此,您需要更改JavaScript以包含if条件,并注意某些响应.
To do that, you would want to alter your javascript to contain an if condition, and to watch for certain responses.
我建议将您的响应修改为json,以便您可以传回不同的信息(例如成功状态,重定向URL或您可能需要的其他信息).
I would recommend modifying your responses to be json, so that you can pass back different information (such as a success status, as well as a redirect url, or other information you might want).
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
var response = $.parseJSON(data);
if (response.redirect) {
window.location = response.redirect_url;
} else {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
}
});
});
对于您的add.php文件,您需要将其更改为类似以下内容:
As for your add.php file, you'll want to change this to be something more like so:
$json = array(
'redirect' => 0,
'url' => '',
}
if (...condition for redirect...) {
$row = mysqli_fetch_array($result);
$id = $row['id'];
$json['redirect'] = 1;
$json['redirect_url'] = "Location: http://localhost/manage/card.php?id=$id";
}
echo json_encode($json);
die();
这篇关于通过Ajax时,标头不会重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!