gpt4 book ai didi

php - AJAX 表单仅重新加载页面

转载 作者:行者123 更新时间:2023-11-30 17:58:38 25 4
gpt4 key购买 nike

我查阅了有关将 ajax 与表单一起使用的各种解释,并将整个程序精简为仅让表单与 php 对话,但它非常固执...

形式:

<form method="get" action="">
Name:<input type="text" name="uname" id="uname"><br>';
<input type="submit" onclick="addcomment()" value="Post">
</form>
<a href="" onclick="addcomment()">Test</a>

JavaScript:

function addcomment()
{

if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();}
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.write(xmlhttp.responseText);
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}

PHP:

<?php
echo 'test';
?>

它不传递任何信息,应该只在屏幕上写“test”,而是重新加载 html 页面,在 'get' information(test .html?uname=)。这在 anchor 标记中工作正常,除非我在尝试表单后尝试它(即,将 'get' 信息添加到页面名称)。我确定我缺少一些基本的东西。你能帮帮我吗?

谢谢。

附言我不会使用 jquery。

最佳答案

添加评论函数需要返回false,告诉浏览器不要执行默认的发布表单 Action 。目前正在发生的事情是浏览器正在执行您的功能,然后立即提交表单,使 xmlhttprequest 没有时间执行。

关于php - AJAX 表单仅重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17588542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com