gpt4 book ai didi

Javascript/AJAX 引用错误 : x is not defined

转载 作者:行者123 更新时间:2023-11-29 10:49:33 25 4
gpt4 key购买 nike

我有一个 jQuery 函数,它从 PHP 生成的复选框中获取值并通过 AJAX 发送它。顺便说一句,该值始终是一个单词,只有字母。下面是脚本。

<script type="text/javascript">
$(document).ready(function() {
$("input:checkbox").on("click", function () {
step = this.value;
//document.getElementById("test").innerHTML = step;
responseArray = [];

xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
responseArray = eval("(" + xmlhttp.responseText + ")");
document.getElementById("test").innerHTML = responseArray;
}
}

xmlhttp.open("GET", "checkbox.php?step="+step, true);
xmlhttp.send();
});
});
</script>

以上代码导致“ReferenceError:[this.value] 未定义”。 [this.value] 是实际值,它会根据选中的框而变化。如果您注意到上面代码中的第 5 行,当我没有注释掉该行时,它会在“test”中为 step 变量显示正确的值,因此它是在那之后的内容。下面是 checkbox.php 文件,完全简化为几乎没有,但它仍然会导致错误。

<?php       
$step = $_GET["step"];
echo "[" . $step . "]";
?>

最佳答案

正如我所见,您使用的是 Jquery,因此您应该使用 JQuery 的 AJAX 对象。它大大简化了请求:

$.ajax({
url: 'checkbox.php?step=',
success: function(data) {
alert(data);
}
});

http://api.jquery.com/jQuery.ajax/

现在您的问题似乎是您没有正确获取复选框的值。复选框打开或关闭。以下是获取各种参数的方法:

$(document).ready(function () {
$("input:checkbox").on("click", function () {
var checkboxID = $(this).attr("ID"); // Returns the ID of the checkbox
var isChecked = $(this).is(':checked'); // Returns true or false

alert($(this).attr("ID") + " is " + isChecked);
});
});

因此您的最终代码可能类似于:

$(document).ready(function () {
$("input:checkbox").on("click", function () {
var checkboxID = $(this).attr("ID"); // Returns the ID of the checkbox
var isChecked = $(this).is(':checked'); // Returns true or false

$.ajax({
url: 'checkbox.php?step=' + isChecked ,
success: function(data) {
alert(data);
}
});
});
});

(未经测试的代码)会向 url checkbox.php?step=true 发送请求

还有来自 2+2 的问候 :D

关于Javascript/AJAX 引用错误 : x is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13148302/

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