表單裡使用者名稱和密碼兩個屬性,單擊按鈕觸發AJAX函數,這個AJAX函數提取表單中“使用者名稱”和“密碼”的值發送到背景程式驗證,php寫的背景程式,php程式分別對“使用者名稱”和“密碼”進行驗證,使用者名稱出錯給出提示,傳回給ajax,顯示到中,同理密碼出錯,顯示到中,現在使用者名稱和密碼能夠正確傳到PHP程式中,做出正確驗證,但是xmlHttp.responseText,如何能實現上面的效果呀?急!!!
回複討論(解決方案)
貼出你的代碼!
你需要在回呼函數中有條件的對不同的目標賦值,那就要回傳有控制資訊
// JavaScript Documentvar xmlHttp;function S_xmlhttprequest(){if(window.ActivXObject){xmlHttp=new ActiveXObject('Mcrosoft.XMLHTTP');}else if(window.XMLHttpRequest){xmlHttp=new XMLHttpRequest;}}function php100(){S_xmlhttprequest();user=document.myform.user.value;pwd=document.myform.pwd.value; var postStr = 'user='+ user+'&pwd='+pwd;xmlHttp.open('POST','login3.php',true); //定義傳輸的檔案HTTP頭資訊 xmlHttp.onreadystatechange=byphp;xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); //發送POST資料 xmlHttp.send(postStr);}function byphp(){var byphp100=xmlHttp.responseText;document.getElementById('userInfo').innerHTML=byphp100;}// JavaScript Document// JavaScript Document
form name="myform" method="post" action=""> 使用者名稱:
密 碼:
“使用者名稱”驗證返回的資訊顯示到userinfo那個div中,密碼顯示到passinfo那個div中;代碼應該怎麼改?希望詳細些,新手謝謝了!
你沒有回傳啊
var byphp100=xmlHttp.responseText;
document.getElementById('userInfo').innerHTML=byphp100;這不是回傳處理了嗎?
function byphp(){ var byphp100=xmlHttp.responseText; if(/使用者/.test(byphp100)) document.getElementById('userInfo').innerHTML=byphp100; else document.getElementById('passInfo').innerHTML=byphp100;}
index.html
無標題文檔
使用者名稱:
密碼
ajax.js
var http_request;
function send_request(url,method) {
http_request = false;
if(window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
window.alert("不能建立XMLHttpRequest對象執行個體.");
return false;
}
switch(method){
case 1:http_request.onreadystatechange = chk;break;
}
http_request.open("GET", url, true);
http_request.send(null);
}
function check(){
send_request("check.php?action="+document.getElementById('pw').value,1);
function chk() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
document.getElementById("user").innerHTML="";
document.getElementById("user").value=http_request.responseText;
} else {
alert("您所請求的頁面異常。");
}
}else {
document.getElementById("user").innerHTML="正在讀取資料中……";
}
}
check.php
if(存在){
echo"正確";
}else{
echo "不正確";
}
?>
check.php中判斷下$_POST['username']和$_POST['pw']
function byphp(){ var byphp100=xmlHttp.responseText; if(/使用者/.test(byphp100)) document.getElementById('userInfo').innerHTML=byphp100; else document.getElementById('passInfo').innerHTML=byphp100;}
代碼運行,咋還是不能將“使用者名稱”和“密碼”驗證返回資訊顯示到不同的div中?回傳控制資訊怎麼寫?謝謝!--新手!
傳json吧
留名! 用jquery不是更好嗎