Ajax将请求结果返回到整个屏幕而不是指定的textarea

时间:2013-05-31 20:47:56

标签: php ajax

这个ajax测试应该(通过约2小时的意愿)将请求结果返回到textarea。请求是在同一页面上进行的,我在主体顶部有一个$ _POST isset测试来检查请求是否来自我的POST请求(我需要将代码全部放在一个文件中)。结果是“文本出现在textarea框中”是自己返回的,并没有放在textarea中。

//name of this page is testing.php  

<html>
<head>
function loadXMLDoc()
{
var xmlhttp;

xmlhttp=new XMLHttpRequest();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("testTextarea").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.open("POST","testing.php",true);
xmlhttp.send("test");
}

</head>

<?
if (isset($_POST["testName"])) {
die("text to appear in the textarea box");
}
?>

<body>


<form action="testing.php" method="POST" onsubmit="loadXMLDoc(this.form); return false;">
<input class="command" type="text" name="testName" />
<div><textarea id="testTextarea"></textarea></div>


</body>
</html>

1 个答案:

答案 0 :(得分:2)

尝试将die()移动到顶部,以便在die()

之前不输出任何其他内容
<?
if (isset($_POST["testName"])) {
die("text to appear in the textarea box");
}
?>

<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;

xmlhttp=new XMLHttpRequest();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("testTextarea").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("POST","testing.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("testName=blah");
}
</script>

</head>

<body>


<form action="testing.php" method="POST" onsubmit="loadXMLDoc(this.form); return false;">
<input class="command" type="text" name="testName" />
<div><textarea id="testTextarea"></textarea></div>
</form>

</body>
</html>
相关问题