php - AJAX 与 PHP 表单提交

标签 php html ajax forms

我最初有一个这样设置的表单(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 的正确方法是什么。

谢谢

最佳答案

我在原始 js 中做的 ajax 还不够多,无法在这里提供教程,所以我打算使用 jquery。然而,我展示的任何东西都可以用原始的 javascript 完成,所以也许其他人会好心地向您展示一个原始的实现。

首先,您应该使用 POST 而不是 GET 进行登录。其次,正如我在评论中所说,您应该使用登录页面的实际 URL 作为操作。这样,无论出于何种原因没有 JS 的用户仍然可以登录。最好通过绑定(bind)到表单 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);
 }

关于php - AJAX 与 PHP 表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5387494/

相关文章:

php - 如何跳过 Codeception cest 测试

PHP 问题 : using if statement

php - 尝试将 base64(图像)文件保存到服务器,它是空的

ajax - 使用 AJAX 有什么缺点吗?

Nodejs 中的 jquery ajax 无法使用 https 获取/发布

PHP DOTNET() 无法从 "System"程序集加载

php - PayPal mc_gross 格式编号?

html - 悬停时更改底层 div 的背景

php - MIME 类型欺骗

javascript - 文档加载后移动 DFP 广告管理系统广告