如何使用jQueryAjax和php响应重定向
我有以下ajax和php。我想根据使用php脚本输出的结果将用户重定向到另一个页面。Php成功地将json返回到浏览器,但不知何故,我无法将响应url返回到js ajax以进行重定向。它总是将我重定向到/未定义。我的代码有什么问题如何使用jQueryAjax和php响应重定向,php,jquery,ajax,response,Php,Jquery,Ajax,Response,我有以下ajax和php。我想根据使用php脚本输出的结果将用户重定向到另一个页面。Php成功地将json返回到浏览器,但不知何故,我无法将响应url返回到js ajax以进行重定向。它总是将我重定向到/未定义。我的代码有什么问题 jQuery.ajax({ type: "POST", url: "../custom_scripts/anmeldung_zurueckziehen.php", data: { anmeldung_id: anmeldung_id },
jQuery.ajax({
type: "POST",
url: "../custom_scripts/anmeldung_zurueckziehen.php",
data: { anmeldung_id: anmeldung_id },
success: function(response){
//alert (response.redirect);
if (response.redirect) {
window.location.href = response.redirect;
}else {
// Process the expected results...
}
}
})
这就是php
$arr = array ('redirect'=>true,'redirect_url'=>'https://mypage.de/no-
access/');
echo json_encode($arr);
希望这有助于:
jQuery.ajax({
type: "POST",
url: "../custom_scripts/anmeldung_zurueckziehen.php",
data: { anmeldung_id: anmeldung_id },
success: function(response){
response = JSON.parse(response);
if (response.redirect) {
window.location.href = response.redirect_url;
}else {
// Process the expected results...
}
}
})
您缺少用于解码响应的
ajax
的dataType
属性:
jQuery.ajax({
type: "POST",
dataType: "json",
url: "../custom_scripts/anmeldung_zurueckziehen.php",
data: { anmeldung_id: anmeldung_id },
success: function(response) {
//console.log(response.redirect);
if (response.redirect) {
window.location.href = response.redirect_url;
} else {
// Process the expected results...
}
}
})
有两种方法可以做到这一点
第一种方法是-在Php中使用JSON头,如下所示
header('Content-Type: application/json');
JSON.parse(response);
上面将返回带有JSON头的JSON字符串,jquery将自动为您解析它,您的回调函数将具有适当的对象
第二种方法是-在javascript中使用JSON.parse,如下所示
header('Content-Type: application/json');
JSON.parse(response);
上面将基本上将json字符串解析为Javascript对象
确保从后端设置JSON头时不进行解析。response.redirect的值是多少?您可以添加到问题中吗?只需查看您得到的
console.log(response)
-永远不要使用警报(对象)
,因为这是无用的。如果响应是一个对象,那么继续,如果它是一个字符串(json格式),那么您需要解析它或者让服务器正确响应。关键是,只要看看你所拥有的东西,这应该是显而易见的。非常感谢!我知道这是一种数据类型,我必须以某种方式转换它。。。