简体   繁体   English

javascript ajax登录表单处理

[英]javascript ajax login form handling

Im working on an ajax form to show errors without reloading the page. 我正在处理ajax表单以显示错误,而无需重新加载页面。 So if everything is good, the user we be redirected to home.php . 因此,如果一切都很好,我们会将用户重定向到home.php At the moment the user will also be redirected when there is an error. 当出现错误时,此刻用户也将被重定向。

This is my code so far: 到目前为止,这是我的代码:

index.php: index.php文件:

<script>
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements); 

var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            window.location.replace("/index.php");
        }
    }
    xmlHttp.open("post", "login.php"); 
    xmlHttp.send(formData); 
}  
</script>

login.php 的login.php

<?php 
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!$user->logUser($$_POST['username'], $_POST['password'])) {
        echo 'ok';
    } else {
        echo 'not ok';
    }
}   
?>

Remove loop from the code and pass elements in FormData() because passing element will take all the fields inside the form 从代码中删除循环并传递FormData() elements ,因为passing element将占用表单内的所有字段

var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements); 

Throw a 401 error if it fails login, this will stop the redirect. 如果登录失败,将引发401错误,这将停止重定向。

<?php 
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!$user->logUser($$_POST['username'], $_POST['password'])) {
        echo 'ok';
    } else {
        header("HTTP/1.1 401 Unauthorized");
        exit;
    }
}   
?>

do you know jquery ? 你知道jQuery吗? jquery w3 school search on google avaible Google上的jquery w3 school search可用

$('#data-div-id').load('www.sdasd .php ? or whatevver');

    function tmp_func_sil_ok(e){
  $.ajax({type:"GET",url:"go.php",data:{'snf_sil':e},success: function(e){msg_("<h3>Başarılı</h3>");}});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM