【问题标题】:How to output content and redirect using ajax and jquery?如何使用 ajax 和 jquery 输出内容和重定向?
【发布时间】:2012-03-12 20:56:02
【问题描述】:

我正在使用 jquery 构建一个注册表单,它应该通过 Ajax 处理请求。 我的代码:

$.ajax( 
{ 
    type: "POST", 
    url: "http://www.example.com/register.php", 
    data: $("#register-form").serialize(),
    cache: false,
    success: function(message)
    {   
                    $("#reg_notification").html(message).fadeIn(400);               
    }           
});

现在,如果电子邮件地址无效,则 register.php 应该输出错误,并将其放入 div reg_notification 中。如果没有出现错误,则应将用户重定向到“欢迎页面”。但重要的是这个页面并不总是静态的,所以换句话说,我不能在 jquery 代码中使用 location.href 但想使用

header("Location: http://www.example.com")

在 PHP 中。问题是用户不会被重定向,但www.example.com 的内容将被放入 div reg_notification 中。

我在这里发现了一个类似的问题:How to manage a redirect request after a jQuery Ajax call,但不同之处在于他们使用的是 json,由于我的服务器,我无法使用它,而且它们也在 javascript 内部而不是 php 文件中重定向。

【问题讨论】:

  • 您不能在 PHP 文件中重定向并期望浏览器也重定向。您可以将整个页面替换为请求的结果。
  • 你有一个网站的例子可以满足你的要求吗?
  • @phpheini 当然,看看你链接的问题。
  • @AdrianLynch 是的,例如twitter.com/signup。至少我希望它是这样工作的,但我不确定他们使用的是什么方法。

标签: php jquery ajax redirect


【解决方案1】:

标头重定向不可能。

使用类似的东西:

...
success: function(message)
{   
     $("#reg_notification").html(message)
          .fadeIn(400, function() {window.location = "url"});
}

success: function(response)
{   
     if (response.success) {
          $("#reg_notification").html(response.message)
               .fadeIn(400, function() {window.location = response.redirectTo; } );
     } else {
          // somethings else
     }
}   

在 php 中:

header("Content-type: application/json");
echo json_encode(array(
    "success" => true,
    "message" => "some message",
    "redirectTo" => "my url"
));

更新 标头重定向不可能,因为 XMLHttpRequest 透明地跟随重定向 url 以获得结果。见there

【讨论】:

  • 即使发生错误,您的第一个示例也会始终重定向我。在第二个示例中,我将如何告诉脚本重定向到哪里?
  • 我的服务器上现在有 json,所以我尝试了这个,但我不明白为什么它不起作用:$.ajax( { type: "POST", url: "http://www.example.com/register.php", data: $("#register-form").serialize(), dataType: "json", success: function(data, textStatus) { if (data.redirect) { window.location.replace(data.redirect); } else { $("#signin_message").replaceWith(data.form); } } }); 然后在 php 中:header("Content-type: application/json"); echo json_encode(array( "success" => true, "form" => "some message", "redirect" => "http://www.example.com" ));
  • 第一步添加console.log(data);并检查结果..如果数据有效的 json 对象然后尝试 window.location = data.redirect...
猜你喜欢
  • 2015-07-18
  • 2022-08-14
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2012-04-12
  • 1970-01-01
相关资源
最近更新 更多