不确定这是否可行但我有一个页面用AJAX提交表单,如果它满足某些条件,它应该自动将用户带到另一个页面。 在标题标记之前输出NOTHING只是一堆条件。
问题:标题重定向不起作用……
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: https://localhost/manage/card.php?id=$id");
您在问题中指出在某些条件下 ,您需要重定向。
要做到这一点,您可能希望更改您的javascript以包含if条件,并观察某些响应。
我建议您将响应修改为json,以便您可以传回不同的信息(例如成功状态,重定向url或您可能需要的其他信息)。
$('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文件,你会想要更改它更像是这样:
$json = array( 'redirect' => 0, 'url' => '', } if (...condition for redirect...) { $row = mysqli_fetch_array($result); $id = $row['id']; $json['redirect'] = 1; $json['redirect_url'] = "Location: https://localhost/manage/card.php?id=$id"; } echo json_encode($json); die();
只有在将任何正文发送到浏览器之前才能修改标题(因此名称标题/正文)。 由于您已将AJAX发送到浏览器,因此无法再修改标头。 但是,您可以通过AJAX调用add.php
脚本返回$id
参数。 然后可以在JavaScript中使用该参数来重定向页面: window.location = 'https://localhost/manage/card.php?id=' + id
。
有关PHP header()
更多信息: http : //www.php.net/manual/en/function.header.php
AJAX
$('form').on('submit', function (e) { e.preventDefault(); $.ajax({ type: 'post', url: '_ajax/add.php', data: $('form').serialize(), success: function (data) { window.location = 'https://localhost/manage/card.php?id=' + data; } }); });
add.php
$row = mysqli_fetch_array($result); $id = $row['id']; echo $id; exit;
您似乎对AJAX的工作方式缺乏了解。 Ajax简介 。
您的重定向似乎无法正常工作的原因是因为Ajax调用不会直接影响您的浏览器。 这是一个幕后的电话。
要从AJAX调用中获取数据,您需要对返回的数据执行某些操作。
success: function (data) { $("input").val('Company Name'); $("form").hide(); //You need to do something with data here. $("#myDiv").html(data); //This would update a div with the id myDiv with the response from the ajax call. getInfo(); }
以上就是jQuery教程分享标题在通过ajax时不会重定向相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/jquerytutorial/532629.html