javascript 使用 AJAX 提交登录表单并获得响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28610931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:16:08  来源:igfitidea点击:

Submit Login Form Using AJAX and get response

javascriptphpjqueryajaxcurl

提问by slk

I am trying to build a front end HTML page that takes in a username and password and then uses a javascript function to show response depending on the answer received from the server. I am a super noob when it comes to web development so can anyone help me correct my code ? Thank you

我正在尝试构建一个前端 HTML 页面,该页面接收用户名和密码,然后使用 javascript 函数根据从服务器收到的答案显示响应。在 Web 开发方面,我是一个超级菜鸟,所以有人可以帮我纠正我的代码吗?谢谢

This is my index.php

这是我的 index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <type="text/javascript"></script>
        <script type="text/javascript" src="jquery.js"></script>
        <link rel="stylesheet" href="styles.css" type="text/css" />
        <title>Login Form</title>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#login").click(function(){
                    username=$("#user_name").val();
                    password=$("#password").val();

                    $.ajax({
                        type    : "POST",
                        url     : "login.php",
                        data    : "username="+username+"&password="+password,
                        success : function(html){
                            if(html=='true'){
                                $("#add_err").html("right username And password");
                                //$("#login_form").fadeOut("normal");
                                //$("#shadow").fadeOut();
                                //$("#profile").html("<a href='logout.php' class='red' id='logout'>Logout</a>");    
                            }else{
                                $("#add_err").html("Wrong username And password");
                            }
                        },
                        beforeSend:function(){
                            $("#add_err").html("Loading...")
                        }
                    });
                    return false;
                });
            });
        </script>
    </head>
    <body>
    <?php session_start(); ?>
        <div id="profile">
            <?php if(isset($_SESSION['user_name'])){ ?>

            <?php } ?>
        </div>
    </body>

    <?php if(empty($_SESSION['user_name'])){ ?>
    <div class="container" id="login_form">
        <section id="content">
            <form action="login.php">
                <h1>Login Form</h1>
                <div>
                    <input type="text" placeholder="Username" required="" id="user_name"  name="user_name"/>
                </div>
                <div>
                    <input type="password" placeholder="Password" required="" id="password"  name="password"/>
                </div>
                <div class="err" id="add_err"></div>
                <div>
                    <input type="submit" value="Log in" id="login"  />
                </div>
            </form>
            <div class="button"> </div> 
        </section>
    </div>
    <?php } ?>

</html>

And this is my login.php code which uses curlto forward username/pass to appropriate url

这是我的 login.php 代码,用于curl将用户名/传递转发到适当的 url

<?php

session_start();
$url =  http://    //url that recieves username/password and responds if credentials are correct after contacting database
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;

?>  

回答by David D

javascript

javascript

$("#login").click(function(){
  $.ajax({
    type: 'POST', 
    url: 'login.php', 
    dataType: 'json',
    data: $('#Form').serialize(),
    success: function (x) {                
      $("#add_err").html(x.response);
    },
    beforeSend:function(){
      $("#add_err").html("Loading...")
    }
  });
  return false;
});

html form

html表单

   <form id="Form" action="login.php">
        <h1>Login Form</h1>
        <div>
            <input type="text" placeholder="Username" required="" id="user_name"  name="user_name"/>
        </div>
        <div>
            <input type="password" placeholder="Password" required="" id="password"  name="password"/>
        </div>
            <div class="err" id="add_err"></div>
        <div>
                <input type="submit" value="Log in" id="login"  />
        </div>
    </form>

php

php

<?php
session_start();
header('Content-Type: application/json');
$url =  http://    //url that recieves username/password and responds if     credentials are correct after contacting database
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$output=array(); 
$output['response']=$result;    
echo json_encode($output);
?>  

回答by Jake Bathman

Alright, first things first: you can use action="form.php"OR the click handler $("#login").click(function(){});. Using both is redundant and will make your javascript form checker void.

好的,首先要做的是:您可以使用action="form.php"OR click handler $("#login").click(function(){});。使用两者都是多余的,并且会使您的 javascript 表单检查器无效。

So go ahead and remove action="login.php".

所以继续删除action="login.php"

Next step is making sure your login.phpscript is receiving everything correctly. For debug purposes, add

下一步是确保您的login.php脚本正确接收所有内容。出于调试目的,添加

var_dump($_POST);
exit();

To the top of login.php, then add

到 的顶部login.php,然后添加

console.debug(html); 

To the top of your ajax successfunction. That'll show you in the console what the PHP script is seeing for $_POSTvariables.

到你的 ajaxsuccess函数的顶部。这将在控制台中向您显示 PHP 脚本看到的$_POST变量。

Hopefully that helps you get started on diagnosing whatever issue is going on.

希望这可以帮助您开始诊断正在发生的任何问题。