//關鍵:點選登入按鈕後,Ajax方法判斷,下面為login.php包含的login.js程式碼
function chklg() {
if ($('lgname').value == '') {
alert('輸入姓名');
$('lgname').focus();
return false;
}
if ($('lgchk').value != $('chknm').value) {
alert("驗證碼錯誤");
$('lgchk').focus();
return false;
}
//關鍵:Ajax獲取user_login_chk.php資料
url = 'user_login_chk.php?act=' + (Math.random()) + '&name=' + $('lgname').value + '&pwd=' + $('lgpwd').value;
xmlhttp.open('get', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
msg = xmlhttp.responseText;
//關鍵:用eval將返回的json字串msg轉為json,並測試json,jsonobj.name
var jsonobj=eval('('+msg+')');
//或者下面兩句同樣效果
var jsonobj='';
eval('jsonobj='+msg+';');
alert(jsonobj.name);
$('name').innerHTML = jsonobj;
if (msg == '1') {
alert("登入成功");
location = "test.php"
}
else {
alert("登入失敗");
}
}
}
}
下面為user_login_chk.php程式碼
<?php
//只是測試用
session_start();
header('Content-Type:text/html;charset=gb2312');
include_once 'conn/conn.php';
$name = $_GET['name'];
$pwd = $_GET['pwd'];
if(!empty($name) && !empty($pwd)){
$sql = "select name from tb_member where name = '".$name."'";
$num = $conne->getRowsNum($sql);
//$student為測試用的php陣列,
$student = array("name"=>"lisheng","age"=>"35");
$studentJson = json_encode($student);
if($num == 0 || $num == '' ){
$reback = $studentJson;
}else{
$reback = $studentJson;
}
}
echo $reback;
?>