gpt4 book ai didi

php - 单击并输入的不同行为

转载 作者:行者123 更新时间:2023-11-29 16:20:40 25 4
gpt4 key购买 nike

当点击提交按钮时,ajax 工作并且调用了 php 页面(不刷新),但是当按下 enter 时它刷新页面并且脚本不起作用,并且只出现 ?txtname=(INPUTED TEXT)在页面 URL 的末尾。

ajax代码:

var time_variable;
var root2 = location.protocol + '//' + location.host + '/testing.php';

function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}var root = location.protocol + '//' + location.host;
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}

var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object

function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST",root2,true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value); //Posting txtname to PHP File
}
}

function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}

html部分:

<body>
<form name="myForm">
<table>
<tr>
<td>Enter Name</td>
<td><input type="text" name="txtname" id="txtname" value="<?php echo $f ?>" /></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Submit" onclick="ajaxFunction();" /></td>
</tr>
</table>
</form>
<div id="message" name="message"></div>
</body>

最佳答案

您需要将onsumbit 属性添加到您的表单:

<form name="myForm" onsubmit="ajaxFunction(); return false;">

return false; 是为了防止页面刷新(即真正提交而不是 ajax)。

关于php - 单击并输入的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10737370/

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