【问题标题】:Jquery, Ajax form and redirectionJquery、Ajax 表单和重定向
【发布时间】:2009-08-15 14:30:29
【问题描述】:

好的,

我需要将 ajax 用于一些花哨的弹出窗口和验证内容,但如果形式上一切正常,我想避免 javascript 重定向。

这是基本简单的场景。

我们有动态网站和一些用户登录表单。逻辑(用户是否存在,密码是否正确等)位于服务器端。

服务器伪代码如下所示:

$username,$password; //form user input

if (authenicate($user,$password)){
   redirect('myaccount');
}
else {
   print 'Wrong username and/or password'; //this should be displayed in the popup.
}

现在如果我使用 ajax 显示服务器打印的内容,如何告诉前端将重定向留给服务器端!?

我以愚蠢的方式解决了这个问题(因为我有大约 15 种不同的形式)。如果答案表单服务器是例如“LOGGED”,我会使用 javascript 重定向。

顺便提一下,我使用 jQuery 和这个插件 http://malsup.com/jquery/form/。 一些示例代码在这里: http://pastie.org/584993

我相信你会明白我的需要,我会接受所有的建议和答案 :) 谢谢!

【问题讨论】:

    标签: jquery ajax webforms


    【解决方案1】:

    将 JSON 发送回客户端。有一个 Status 参数、一个 Message 参数和一个 Url 参数。成功时将 Status 设置为 true,并将 Url 设置为指向的页面。出错时,将状态设置为 False,将消息设置为错误消息。在客户端,使用 Status 来决定是重定向还是弹出消息

     $.ajax({
         url: '/login.php',
         dataType: 'json',
         data: $('form').serialize(),
         type: 'post',
         success: function(data) {
             if (data.Status) {
                location.href = data.Url;
             }
             else {
                alert( data.Message );
             }
         }
     });
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      相关资源
      最近更新 更多