ホームページ  >  記事  >  バックエンド開発  >  ajax POST 経由で値を渡しますが、戻り値は空です

ajax POST 経由で値を渡しますが、戻り値は空です

WBOY
WBOYオリジナル
2016-06-23 13:58:43768ブラウズ

Ajax にアクセスするのは初めてなので、簡単な例で練習したいと思います
Index.php にはドロップダウン リストがあり、異なるクラスを選択して異なる学生情報を返します
コードは次のとおりです:

<?php	//从数据库把班级名称取出来放入下拉列表中	mysql_connect("localhost","root","root") or die("数据库连接失败");	mysql_select_db("studentmanage") or die("数据库不存在");							$sql="select * from class";	$rs=mysql_query($sql);	$info=array();	while($row=mysql_fetch_assoc($rs)){		$info[]=$row;	}?><!doctype html><html>	<head>		<title>查询学生信息</title>		<meta http-equiv="content-type" content="text/html;charset=utf-8"/>		<style type="text/css">				</style>		<script type="text/javascript">			var xmlhttprequest;;			function getMessage(){								if(window.ActiveXObject){					xmlhttprequest=new ActiveXObject("Microsoft.XMLHTTP");				}else{					xmlhttprequest=new XMLHttpRequest();				}								if(xmlhttprequest){					var url="result.php";					var cid=document.getElementById("class").value;					var show=document.getElementById("info");					var data="class=cid";					xmlhttprequest.open("post",url,true);					xmlhttprequest.setRequestHeader("content-type","application/x-www-form-urlencode");					xmlhttprequest.onreadystatechange=function(){						if(xmlhttprequest.readyState==4){							if(xmlhttprequest.status==200){								var info=xmlhttprequest.responseText;								if(info==""){									show.value="你好,你查询的班级暂时还没有学生";								}else{									show.value=info;								}							}						}else{							alert("error");						}					}					xmlhttprequest.send(data);				}			}		</script>	</head>	<body>		<div id="content">			<h1>				请选择班级:				<select name="class" id="class" onchange="getMessage()">					<option value="" selected>choose class</option>					<?php foreach($info as $v){?>					<option value="<?php echo $v['cid'];?>"><?php echo $v['cname'];?></option>					<?php }?>				</select>			</h1>			<div id="info"></div>		</div>	</body></html>


result.php を通じてデータベースにクエリを実行し、学生の情報を返すコードは次のとおりです:
<?php	//header("content-type:text/html;charset=utf-8");	header("Content-type:text/xml;charset=utf-8");	header("Cache-Control:no-cache");	$class=$_POST['class'];		mysql_connect("localhost","root","root") or die("数据库连接失败");	mysql_select_db("studentmanage");	mysql_query("set names utf-8");	$sql="select * from student where cid='$class'";	//$sql="select * from student where cid=3";	$rs=mysql_query($sql);	$info=array();	while($row=mysql_fetch_assoc($rs)){		$info[]=$row;	}		$result="<table><tr><td>学号</td><td>姓名</td><td>住址</td><td>班级</td></tr>";	foreach($info as $v){		$result.="<tr><td>{$v['sid']}</td><td>{$v['name']}</td><td>{$v['address']}</td><td>{$v['cid']}</td></tr>";	}	$result.="</table>";	echo $result;?>


result.php だけをテストしましたが、データベースから対応する情報を取得できることは間違いありません。取得した情報をindex.phpに返すことはできません
問題を見つけるのを手伝ってください


ディスカッションに返信(解決策)

result.php
出力内容を直接返すことはできません。json_encodeを使用する必要があります。返されたデータを処理します

例: ルックアップ テーブル データが配列に入れられ、次に: echo json_encode($arr);

クエリが正常であっても、div の値を設定します。 div はビューに直接表示されないため、効果を見ることはできません。
必要なものは innerHTML である必要があります

result.php
出力コンテンツを直接返すことはできません。返されたデータを処理するには json_encode を使用する必要があります

例: ルックアップ テーブル内のデータは配列に入れられ、 echo json_encode($ arr);



ajax には 3 つの戻り形式がありますか?それぞれテキスト、xml、json です
ここではテキスト形式を使用していますが、これの何が問題なのかわかりません 少なくともコールバック関数に var show=document.getElementById("info"); を入れる必要があります。

to div 値を設定しますか? クエリが正常であっても、div の値はビューに直接表示されないため、効果はわかりません。

必要なものは innerHTML であるはずです


はい、その通りです (私の JS 基盤はあまり良くありません==)。あなたの言ったことに従って変更し、段階的にデバッグしました:

<?php	//从数据库把班级名称取出来放入下拉列表中	mysql_connect("localhost","root","root") or die("数据库连接失败");	mysql_select_db("studentmanage") or die("数据库不存在");							$sql="select * from class";	$rs=mysql_query($sql);	$info=array();	while($row=mysql_fetch_assoc($rs)){		$info[]=$row;	}?><!doctype html><html>	<head>		<title>查询学生信息</title>		<meta http-equiv="content-type" content="text/html;charset=utf-8"/>		<style type="text/css">				</style>		<script type="text/javascript">			var xmlhttprequest;;			function getMessage(){								if(window.ActiveXObject){					xmlhttprequest=new ActiveXObject("Microsoft.XMLHTTP");				}else{					xmlhttprequest=new XMLHttpRequest();				}								if(xmlhttprequest){					var url="result.php";					var cid=document.getElementById("class").value;					//window.alert(cid);					var show=document.getElementById("info");					//window.alert(show);					var data="class="+cid;					//window.alert(data);					xmlhttprequest.open("post",url,true);					xmlhttprequest.setRequestHeader("content-type","application/x-www-form-urlencode");					xmlhttprequest.onreadystatechange=function(){						if(xmlhttprequest.readyState==4){							if(xmlhttprequest.status==200){								var info=xmlhttprequest.responseText;								if(info==""){									show.innerHTML="你好,你查询的班级暂时还没有学生";								}else{									show.innerHTML=info;								}							}						}else{							window.alert("error");						}					}					xmlhttprequest.send(data);				}			}		</script>	</head>	<body>		<div id="content">			<h1>				请选择班级:				<select name="class" id="class" onchange="getMessage()">					<option value="" selected>choose class</option>					<?php foreach($info as $v){?>					<option value="<?php echo $v['cid'];?>"><?php echo $v['cname'];?></option>					<?php }?>				</select>			</h1>			<div id="info">aaa</div>		</div>	</body></html>


Drop -down list 値はjs経由で取得されますが、window.alert(data)を使用してデバッグする場合は問題ありませんが、result.phpの$class=$_POST['class']を介して値を取得する場合は問題ありません。 file_put_contents("D:/WWW/PHPDemo/log.log",$class."rn",FILE_APPEND); を通じて $class の値を log.log ファイルに保存しているため、割り当てられていませんが、それを実行した後は、ファイルを開くと空であり、実行時に次のようなエラーが報告されます: Notice: Unknown Index: class in D:WWWdbDesignprojectresult.php on line
方法に何か問題があるかどうか尋ねたいです。私のajaxはPOSTを通じて値を転送しますか? ?


問題は、値が result.php に渡されないことです。なぜですか?
xmlhttprequest.setRequestHeader("Content-Type","application/x-www-form -urlencode") );

xmlhttprequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

最後に d を 1 つ減らしました

コード行を注意深く読んだと言えます。 =====
この種のエラーをデバッグできる JS デバッグ ツールがあるかどうかはわかりません。探すのにそれほど時間を費やす必要はありません。バグ。 。 。 。

プログラマーは油断しないで、お互い励まし合いましょう

jqueryを使ってみてはいかがでしょうか?

<?php	//header("content-type:text/html;charset=utf-8");	header("Content-type:text/xml;charset=utf-8");	header("Cache-Control:no-cache");	$class=$_POST['class'];		file_put_contents("D:/WWW/PHPDemo/log.log",$class."\r\n",FILE_APPEND);			mysql_connect("localhost","root","root") or die("数据库连接失败");	mysql_select_db("studentmanage");	mysql_query("set names utf-8");	$sql="select * from student where cid='$class'";	//$sql="select * from student where cid=3";	$rs=mysql_query($sql);	$info=array();	while($row=mysql_fetch_assoc($rs)){		$info[]=$row;	}		$result="<table><tr><td>学号</td><td>姓名</td><td>住址</td><td>班级</td></tr>";	foreach($info as $v){		$result.="<tr><td>{$v['sid']}</td><td>{$v['name']}</td><td>{$v['address']}</td><td>{$v['cid']}</td></tr>";	}	$result.="</table>";	echo $result;?>

http://api.jquery.com/jQuery.post/


jquery を使ってみませんか?

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script><script type="text/javascript">var cid=document.getElementById("class").value;var show=document.getElementById("info");$.post("result.php", { class: cid },   function(info){     if(info==""){       show.innerHTML="你好,你查询的班级暂时还没有学生";     }else{       show.innerHTML=info;     }   },"text");</script>

http://api.jquery.com/jQuery.post/


js を始めたばかりですが、フレームワークを使用する前に、より良い js 基盤を構築したいと思っています。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。