【问题标题】:AJAX vs PHP submit of formAJAX vs PHP 提交表单
【发布时间】:2011-07-20 05:43:47
【问题描述】:

我最初有一个这样设置的表单(CSS 样式已被删除)

<form name="LoginForm" action="login.php" method="post">

<input name="email" id="email" type="text"></input>

<input name="password" id="password" type="password"></input>

<input name="login" id="login" type="submit" value="Login"></input>
</form>

它运行良好,login.php 将验证用户信用。但是,这种方法需要页面重定向。我正在尝试将代码迁移到 AJAX,以便我可以查询登录详细信息并留在页面内。 [编辑] 这是我使用的 AJAX 对象

function Ajax(){
    this.xmlhttp=null;  //code below will assign correct request object
    if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
        this.xmlhttp=new XMLHttpRequest();
    }
    else{       // code for IE6, IE5
        this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    this.stateChangeFunction=function(){};  //user must reimplement this

    var that=this;
    this.xmlhttp.onreadystatechange=function(){ //executes the appropriate code when the ready state and status are correct
        if (this.readyState==4 && this.status==200){
            that.stateChangeFunction();     
        }
        else{
            dump("Error");
        }
    }
}

然后我有一个 login.js 函数,我不太清楚如何合并,目前我将它添加到提交按钮的 onclick 事件中:

function login(email,password){
    var ajax=new Ajax();

    //ajax.xmlhttp.open("GET","login.php?LoginEmailField="+email+",LoginPasswordField="+password,true);
    //ajax.xmlhttp.send();
}

您会注意到最后两行是如何被注释掉的,我现在不太确定如何发送参数,但关键是即使这两行被注释掉,整个站点仍然会重新加载。在表单中使用 AJAX 的正确方法是什么。

谢谢

【问题讨论】:

    标签: php html ajax forms


    【解决方案1】:

    我没有在原始 js 中做足够多的 ajax 来提供教程,所以我打算使用 jquery。然而我展示的任何东西都可以用原始的 javascript 来完成,所以也许其他人会很友好地向你展示一个原始的实现。

    首先,您应该使用 POST 而不是 GET 进行登录。其次,正如我在评论中所说,您应该使用登录页面的实际 URL 作为操作。这样无论出于何种原因没有 JS 的用户仍然可以登录。最好通过绑定到表单onSubmit 事件来做到这一点。

    <form name="LoginForm" action="login.php" method="post">
    
    <input name="email" id="email" type="text"></input>
    
    <input name="password" id="password" type="password"></input>
    
    <input name="login" id="login" type="submit" value="Login"></input>
    </form>
    

    使用 jquery:

    function doLogin(event){
      event.preventDefault(); // stop the form from doing its normal post
      var form = $('form[name=LoginForm]');
      // post via ajax instead
      $.ajax({
        url: form.attr('action'), // grab the value of the action attribute "login.php"
        data: form.serialize(), // converts input fields to a query string
        type: 'post',
        dataType: 'text',
        success: function(data){
          /* callback when status is 200
           * you can redirect here ... data is the response from the server, 
           * send the redirect URL in this response
           */
          window.location.href = data;
        },
        error: function(textStatus){
          alert('ERROR');
        }
      });
    }
    
    // bind our function to the onSubmit event of the form
    $('form[name=LoginForm]').submit(doLogin); 
    

    然后在服务器端你可以检查它是否是一个基于 ajax 的请求:

    <?php
    
     // do your login stuff
    
     // set $successUrl to the URL you want to redirect to
    
     // check if its ajax
     if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
       && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
     {
       echo $successUrl;
       exit(0);
     }
     else
     {
        // was a non-ajax request - do a normal redirect
        header('Location: '.$successUrl);
     }
    

    【讨论】:

    • 这看起来很复杂,这是我目前正在采取的方法。我将表单标题更改为&lt;form name="LoginForm"&gt;,然后将提交按钮更改为普通按钮,&lt;input name="button" id="button" type="button" onclick="login();" value="Login"&gt;&lt;/input&gt; 然后在 login() 中手动提取其他输入字段
    • 您实际上在做与我刚刚编写代码相同的事情,只是通过使用非提交输入并从表单中删除action 您不允许未启用 javascript 的用户登录。 ..此外,由于您使用的是 get 而不是 post 您允许任何人只需在浏览器中输入随机用户名和密码即可登录...至少 post 它有点麻烦,尽管您应该使用某种 CSRF 令牌验证...
    • 我明白为什么 get 会出现这个问题,但如果它在每次击键时都不断更新,那不是真的有问题吗?
    • 我不知道你在做什么..击键与它无关..我在谈论将 URL 直接输入到浏览器的位置栏中或在脚本中使用 CURL 来运行攻击...即使使用 POST 也可以授予,除非您有某种验证系统来确保请求响应您的表单
    • 我明白你的意思,我从没想过,因为我想我只是想“当我来到它时,我会越过那座桥”。感谢您的帮助
    【解决方案2】:

    您的代码仅显示HTMLAJAX 使用 javascript 与 PHP 脚本通信。

    所以,只有看到js 代码,才能进行调试。

    【讨论】:

      【解决方案3】:

      要避免默认事件,您必须使用 action='javascript: void(null);' 而不是删除它。

      【讨论】:

      • 我插入了action='javascript: void(null);' 语句,它确实阻止了重新加载。现在,您是否知道如何在提交时正确重定向到 javascript 函数?我应该插入它来代替void(null)(对我不起作用),还是应该将它添加到提交按钮的onclick事件中?谢谢
      • 使用它作为操作使非 js 启用的用户无法登录。你真的应该绑定到formonSubmit 事件,然后从操作中获取 URL。
      • @prodigitalson:我不完全理解。抢什么网址?你的意思是这样的吗:&lt;form name="x" action='javascript: void(null);' method="post" onSubmit='load();'&gt;
      • @puk:我曾经使用 jQuery 处理 AJAX。我所做的是在 javascript 中进行简短验证后使用 $.post$.get 函数。验证是onSubmit 事件。
      • @puk:请参阅我的答案以获取更多详细信息……尽管使用的是 jquery 而不是原始 js。本质上不是绑定到按钮onClick,而是绑定到表单的onSubmit,这将由点击触发...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 2014-02-14
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多