我有一个非常简单的案例,但令我困惑,这里是script =>
<!DOCTYPE html>
<html>
<head>
<title>HI</title>
<link rel="stylesheet" href="./scripts/css/default.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form name="ok" method="post" action="index.php">
<select name="sel" id="sel"><option value="a">1</option><option value="b">2</option><option value="c">3</option></select>
</form>
FIRST PAGE
<div id="as"></div>
<script type="text/javascript">
document.getElementById("sel").onchange = function(){
var doc = false;
if (window.XMLHttpRequest){
doc = new XMLHttpRequest();
}
if(doc){
doc.open("POST","./index.php",true);
doc.onreadystatechange = function(){
if (doc.status==200 && doc.readyState==4){
document.getElementById("as").innerHTML = doc.responseText;
}
};
doc.send("sel=" + document.getElementById("sel").value);
}
};
</script>
<?php
if (isset($_POST['sel'])){
echo $_POST['sel'];
}
?>
</body>
</html>
从这个脚本我希望onselect change返回select元素的值,但它会再次返回整个页面,为什么?有任何想法吗 ?请帮助,谢谢:))
PS。这是自我index.php页面
答案 0 :(得分:0)
创建一个单独的php文件来处理你的ajax请求,这样ajax请求只能显示php文件回显的文本。
这是我的示例代码:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
if (isset($_POST['sel'])){
echo "yeah";
}
}else{die('You are not allowed to access this page!');}