gpt4 book ai didi

php - 无法识别简单的 AJAX 代码

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

我正在尝试开始学习 AJAX,但我已经遇到了一些困难。所以我从简单开始,只是尝试弹出一个警报,显示用户在文本字段中键入的字符串的长度。

HTML:

<form action="/scripts/addemail_fb.php" method="post">
<input type="text" name="email" value="Enter your email here!" />
<input id="submit" type="submit" name="submit" value="Go!" onClick="check(this.form.email.value);"/>
</form>

JS:

function check(email) {


if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}


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

email=encodeURIComponent(email);

req.open("POST","/scripts/addemail.php");

req.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8');

req.send(email);

req.onreadystatechange=function() {

if(req.readyState==4) {

result = req.responseText;

alert("The length of the email is:" + result);

}

}

return false;

}

PHP (addemail.php):

<?php
function check_email($input) {
return strlen($input);
}
$email = urldecode(implode(file('php://input')));
$result = check_email($email);
echo $result;
?>

是的,我已将 JS 包含在该部分中。我几乎直接从教程中得到了这个,所以我不确定发生了什么。我的测试浏览器是 Safari,但我也试过 FF。抱歉,这是显而易见的,因为这是我第一次尝试 AJAX。谢谢!

编辑:抱歉,问题是它只是转到 action="addemail_fb"中描述的文件而不是 JS。

-iMaster

最佳答案

onclick 处理程序更改为 onsubmit(在表单上),如下所示:

<form onsubmit="return check(this.email.value);"> ... </form>

另外,在调用req.send()之前设置你的req.onreadystatechange

关于php - 无法识别简单的 AJAX 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1973124/

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