我无法运行我的简单ajax脚本。代码应该非常简单。ajax脚本是:
<html>
<head><title>Testing ajax</title>
<script type="text/javascript">
function ajax() {
var xmlhttp;
var fname=document.getElementById("fname").value;
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("output").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php?fname="+fname,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" id="fname">
<input type="text" id="lname">
<input type="submit" id="submit" onclick="ajax()">
</form>
<div id="output"></div>
</body>
php脚本是:
<?php
$fname=$_GET['fname'];
echo "<p>Hello ".$fname."</p>";
?>我也尝试过:
xmlhttp.open("POST","ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/pass-data");
xmlhttp.send("fname="+fname);我既不能使用post也不能使用get方法发送数据。我看到的不是很简单的东西吗?
发布于 2012-06-03 12:47:40
它不工作的原因是因为您的输入位于<form>标记中。删除表单标记后,当我尝试将<input type="submit" />控件更改为
<input type="button" onClick="ajax()" value="Submit" />它就像一个护身符一样有效。我怀疑,由于提交时的某些好处、安全问题等等,表单行为的处理方式会有所不同。
发布于 2012-06-03 12:44:59
将输入类型从提交更改为按钮
输入按钮“type=”onclick=...
因为当您点击按钮时,如果type=为“submit”,它会立即提交页面。
https://stackoverflow.com/questions/10867796
复制相似问题