提交表单时刷新PHP / JavaScript登录脚本

时间:2014-04-15 10:20:23

标签: javascript php jquery

我使用以下JavaScript创建了一个登录页面:

    function handleLogin() {
    var form = $("#loginForm");    
    //disable the button so we can't resubmit while we wait
    //$("#submitButton",form).attr("disabled","disabled");
    var e = $("#username", form).val();
    var p = $("#password", form).val();

    console.log("click");
    if(e != "" && p != "") {
        //var str = form.serialize();
        //alert(str);
        $.ajax({ 
                 type: 'POST', 
                 url: 'http://localhost/php/log.php', 
                 crossDomain: true,
                 data:  {username: e, password :p},
                 dataType: 'json', 
                 async: false,

                 success: function (response){ 
                    alert ("response"); 
                    if (response.success) { 
                        alert("you're logged in");
                        window.localStorage["username"] = e;
                        window.localStorage["password"] = md5(p); 
                        //window.localStorage["UID"] = data.uid;           
                        window.location.replace("http://www.google.co.uk");
                    } 
                    else {

                        alert("Your login failed");
                        //window.location("main.html");
                    }


                 },
                 error: function(error){
                     //alert(response.success);
                    alert('Could not connect to the database' + error);
                    window.location = "index.html";
                }
        }); 
    }
    else {
        //if the username and password is empty
        alert("You must enter username and password");

    }
    return false;
    }

和log.php中的PHP是:

        $link = mysql_connect("$host", "$username", "$password") or die("Could not connect to host.");
        mysql_select_db("$db_name", $link) or die("Could not find database.");


       $uname = isset($_POST['username']) ? $_POST['username'] : '';
       $password = isset($_POST['password']) ? $_POST['password'] : '';



        $sql = "SELECT * FROM user WHERE username = '$uname' AND password = '$password'";
        $result=mysql_query($sql);
        $num_row=mysql_num_rows($result);
        $row=mysql_fetch_array($result);


        if (is_object($result) && $result->num_rows == 1) {
        $response['success'] = true;

        }
        else
        {
        $response['success'] = false;
        }

        echo json_encode($response);

         //echo 'OK';

如果组合错误,我希望页面显示一些错误,或者如果它是正确的,则重定向到另一个页面。但是它只是用url中的用户名/密码刷新。

登录表单

<form id="loginForm" method="post">
      <div data-role="fieldcontain" class="ui-hide-label">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" value="" placeholder="Username" />
  </div>
      <div data-role="fieldcontain" class="ui-hide-label">
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" value="" placeholder="Password" />
  </div>
      <input type="submit" value="Login" id="submitButton">
    </form>

3 个答案:

答案 0 :(得分:0)

请按以下方式更改您的html容器

<div data-role="fieldcontain" class="ui-hide-label">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" value="" placeholder="Username" />
  </div>
      <div data-role="fieldcontain" class="ui-hide-label">
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" value="" placeholder="Password" />
  </div>
  <input type="button" value="Login" id="submitButton" onclick="handleLogin()">

因为您使用ajax提交数据,所以您不需要写#34;形式&#34;你的HTML中的标签

单击&#34;提交&#34;将刷新总页数。按钮。所以我改成了&#34;按钮&#34;并在&#34; onclick&#34;中提供ajax方法。属性

示例PHP文件(index.php),我试过没有连接数据库来测试你的场景

<?php
if($_POST){
    if($_POST['username'] == "admin" && $_POST['password'] == "admin"){
        $response['success'] = true;
    }else{
        $response['success'] = false;
    }

    echo json_encode($response);
    exit;
}
?>

修改你的js代码

function handleLogin() {
    var e = $("#username").val();
    var p = $("#password").val();

    if(e != "" && p != "") {
        $.ajax({ 
                 type: 'POST', 
                 url: 'index.php', 
                 crossDomain: true,
                 data:  {username: e, password :p},
                 dataType: 'json', 
                 async: false,

                 success: function (response){ 
                    alert ("response"); 
                    if (response.success) { 
                        alert("you're logged in");
                     } 
                    else {
                        alert("Your login failed");
                    }
                 },
                 error: function(error){
                    alert('Could not connect to the database' + error);
                 }
               }); 
    }
    else {
        alert("You must enter username and password");
    }
    return false;
}

答案 1 :(得分:0)

由于您正在使用jQuery(版本1.10.1),因此您可以将click事件直接绑定到表单提交按钮

$(document).on('click', '#submitButton', function(e) {
   e.preventDefault();

   ... See detailed jsFiddle example ...

   return false;
});

使用preventDefault(),您可以删除“提交”按钮的默认提交行为,因此在表单提交后不会重新加载页面。

还可以使用action等表单属性来提供ajax URL或方法来设置ajax请求类型。

P.S 这种类型的绑定对jQuery 1.6不起作用

jsFiddle example

答案 2 :(得分:0)

试试这个:if(response.responseText)