dongxuxian6930 2013-04-30 16:55
浏览 25
已采纳

Php函数返回始终为零

I've a form with a password field

<form id="form-login" class="row-fluid" novalidate="novalidate" method="post" action="#">
<input class="span12" type="password" name="password" pattern="[0-9 ]{5,15}" />
</form>

when submit the form I do an Ajax call:

...
var data = $('form').serialize();

$.ajax({

    url: "/wp-admin/admin-ajax.php", // wordpress
    type: "POST",
    data: data + '&action=login_check',
    cache: false,

    success: function (html) {           
        $('.loading').hide();

        if ( html == 0 ) {
            $('.undone').fadeIn('slow');
        } else if ( html == 1 ) {
            $('.done').fadeIn('slow');                  
        }
    }
}); 

return false;
...

that check password using this function in functions.php (Wordpress):

function login_check(){

        $pw = 'hello';

        if( md5($pw) == md5($_POST['password']) ){

            $_SESSION['key'] = 1;
            return 1;

        } else {

            return 0;

        }

    die();

}

add_action('wp_ajax_login_check', 'login_check');
add_action('wp_ajax_nopriv_login_check', 'login_check');

and I want that the above function returns 0 or 1 to the success function in the ajax call. But it returns always 0, also when insert the correct password. Where am i wrong?

var_dump($_POST);

array(3) {
  ["password"]=>
  string(5) "hello"
  ["s"]=>
  string(0) ""
  ["action"]=>
  string(11) "login_check"
}
  • 写回答

1条回答 默认 最新

  • dtnrsmi824877 2013-04-30 17:10
    关注

    You check for a Number in your javascript ajax callback handler. But the html param will be acutally a String. Change the callback to:

    if ( html == '0' ) {
        $('.undone').fadeIn('slow');
    } else if ( html == '1' ) {
        $('.done').fadeIn('slow');                  
    }
    

    What happens? You formally, (before edition the question) returned nothing '' on success and '0' an error. But because of the loose typing system of javascript both evaluated to ==0. Check this javascript code:

    ""==0;  // true
    "0"==0; // true
    

    Also change the return statements in PHP into echo statements. Note that the return statement actually outputs nothing:

    if( md5($pw) == md5($_POST['password']) ){
        $_SESSION['key'] = 1;
        echo '1';
    } else {
        echo '0';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题