简体   繁体   English

Ajax不返回任何结果

[英]Ajax does not return any result

My Ajax function does not return any result 我的Ajax函数不返回任何结果

<div id="container">                
    <div id="connexion">
        <form  method="post" action="">
            <input type="text" id="login">
            <input type="password" id="password"><br />
            <input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
            <span id="errormess"></span>
        </form >
    </div>
</div>
$(document).ready(function(){
    $("#ok").click(function() {
        var login = $("#login").val();
        var password = $("#password").val();
        var dataString = 'login='+ login + '&password=' + password;
        $.ajax({ 
            type: "POST",
            url: 'login.php',
            data: dataString,
            dataType: "json",
            success: function(data) {
                if (data == 0) {
                    $('#errormess').html("problem");
                } else { 
                    $('#errormess').html(data);
                }   
            }//success
        });//ajax
        return false;
    });//ok
});//document
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND password=$password'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $userId= $row["id"];
        $today=time();
        $week=strftime('%W',$today) ;
    }
    $arr = array(
        'userId' => $userId,
        'week' => $week,   
     );
    echo json_encode($arr);       
}  

The issue is because the button click is submitting the form in the standard manner, meaning your AJAX request is prevented from completing. 问题是因为单击按钮以标准方式提交表单,这意味着您的AJAX请求无法完成。 It's better practice to hook to the submit event of the form . 最好挂接到formsubmit事件。

Also note that your PHP code will never return 0 , it would be better to have a error handler should the AJAX not complete as expected. 还要注意,您的PHP代码永远不会返回0 ,如果AJAX未按预期完成,最好有一个error处理程序。 Finally, your current code is wide open to attack; 最后,您当前的代码容易受到攻击。 you should look in to using SSL and using prepared statements to avoid SQL injection. 您应该研究使用SSL和使用准备好的语句来避免SQL注入。

That said, here's a fix for your AJAX issues: 也就是说,这是针对您的AJAX问题的修复程序:

<div id="container">                
    <div id="connexion">
        <form id="myform" method="post" action="">
            <input type="text" id="login">
            <input type="password" id="password"><br />
            <input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
            <span id="errormess"></span>
        </form>
    </div>
</div>
$("#myform").submit(function(e) {
    e.preventDefault(); // stop standard form submission

    $.ajax({ 
        type: "POST",
        url: 'login.php',
        data: {
            login: $("#login").val(),
            password: $("#password").val()
        },
        dataType: "json",
        success: function(data) {
            $('#errormess').html(data); 
        }
        error: function() {
            $('#errormess').html("problem");
        }
    });
});

I think you are giving the data parameter wrongly. 我认为您错误地输入了data参数。 It should be like 应该像

var dataString = {"login": login,
                   "password": password}

HTML 的HTML

<div id="container">                
        <div id="connexion">
            <form  method="post" action="">
               <input type="text" id="login">
               <input type="password" id="password">
               <br />
        <input name="Submit" type="button" id="ok" value="OK" class="btn ">;      
               <br /> <br />
               <span id="errormess"></span>
           </form >
        </div>
    </div>

JS JS

$(document).ready(function(){
       $("#ok").click(function(e) {
              e.preventDefault();
              var login = $("#login").val();
              var password = $("#password").val();
              var dataString = {"login": login,
                   "password": password}
              $.ajax({ 
                  type: "POST",
                  url: 'login.php',
                  data: dataString,
                  dataType: "json",
                  success: function(data) {
                     if (data == 0) {
                            $('#errormess').html("problem");
                     } else { 
                            $('#errormess').html(data);
                     }   
                   }//success
                });//ajax
                return false;
            });//ok
     });//document

Also change the input type from submit to button and have and e.preventDefault() in your JS. 同时更改输入类型,从submitbutton ,并有和e.preventDefault()在你的JS。

javascript code : JavaScript代码:

$(document).ready(function(){
        $("#ok").click(function(e) {
            e.preventDefault();
            var data = (this.form).serialize(); // added code 
            $.ajax({
                url: 'login.php',  
                data: data,   
                dataType:'json',  
                type:'POST',  
                async:false, 
                success: function(data) {       
                    if (data.success == 0) {  // added code 
                        $('#errormess').html("problem");
                    } else { 
                        $('#errormess').html(data);
                    }  
                },
                error: function(data) { // if error occured

                }
            });
        });//ok
    });//document

php code : PHP代码:

$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND    
 password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $userId = $row["id"];
        $today = time();
        $week = strftime('%W', $today);
    }
    $arr = array(
        'userId' => $userId,
        'week' => $week,
    );
    echo json_encode($arr);
} else {  // added code 
    $arr = array("success" => '0');
    echo json_encode($arr);
}

Please do check. 请检查。 I have modified the response from PHP as well as jquery code. 我已经修改了PHP和jquery代码的响应。

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

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