通过jQuery.ajax()将变量从PHP页面传递到Javascript页面

时间:2011-04-03 09:53:16

标签: php javascript jquery ajax variables

基本上,我正在调用一个页面(login.php),它检查以确保用户已经过验证并且密码通过我的javascript(init.js)匹配。如果是的话,我在PHP页面中回显“all-good”,它将传递回init.js,在那里它检查是否回显了“all-good”。

显然这是非常不安全的,所以我想做一些像$ verify_string = md5(uniqid($ username));在login.php中,但我无法弄清楚如何将该变量传递回init.js.

有人有什么建议吗?这就是我现在正在做的事情:

init.js

    $.ajax({  
        type: "POST",
        url: "login.php",  // Send the login info to this page
        data: str,  
        success: function(msg){  

        $(".status").ajaxComplete(function(event, request, settings){  

         // show 'submit' button
        $('.submit').show();

        // hide ajax loading gif
        $('.ajax-loading').hide(); 

            if(msg == "all-good") {  // login ok?
             var login_response = '<div id="logged-in">' +
                                    '<img src="img/load-bar.gif">' +
                                    '<br><span style="padding-top: 5px; font-size: .9em;">Logging in...</span>'
                                     '</div>';  

            $('a.modalCloseImg').hide();
            // resize container after processing 
            $('#simplemodal-container').css("width","auto");
            $('#simplemodal-container').css("height","auto");

             $(this).html(login_response); // refers to 'status'

            // redirect after 2 seconds
            setTimeout('go_to_private_page()', 2000); 
             }  
             else {  // error?
             var login_response = msg;
             $('.login-response').html(login_response);
             } 
        });   
    }  
    });

login.php

        // checks the entered pw with the hashed pw in the db
    while($row = $stmt->fetch()) {  
        if (crypt($password, $row['hashed_pw']) == $row['hashed_pw']) {

            $_SESSION['username'] = $username;
            $_SESSION['user_id'] = $row['user_id'];
            $_SESSION['redirect'] = $redirect;
            setcookie('username', $username, time()+3600, '/', '', 0, 0);
            setcookie('user_id', $row['user_id'], time()+3600, '/', '', 0, 0);

            // this is what I want to send back:
            $verify_string = md5(uniqid($username));
            echo $verify_string;

                            // this is what is currently being sent back for verification
                            echo "all-good";

            exit();
        } else {
            $errors[] = "Bad username/password combination. Try again.";
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用数组,然后使用以下php函数在json中进行编码:

  

json_encode

$arr = Array(md5(uniqid("username")), "all-good");
echo json_encode($arr);