这是我的Javascript代码:
const checkbox = document.querySelector("#checkbox");
const button = document.querySelector("#button");
button.addEventListener("click", function(e){
var text = "";
if(checkbox.checked === true){
text = "Is Checked";
}
$.ajax({
url: '/update_if_checked/',
data: {'is_checked': text},
type: 'POST'
}).done(function(response){
console.log(response);
});
});
我收到一个错误,说$.ajax不是HTMLButtonElement中的函数。
这里,checkbox是一个checkbox类型的输入,当id为" button“的按钮被点击时,我想要发送数据,即如果复选框被选中到Django服务器。
我已经在HTML中导入了这个版本的jquery:
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
编辑
抱歉,这个按钮的id只是一个按钮。
HTML:
<div>Check<input type="checkbox" id="checkbox"></div>
<button id="button">Submit</button>
发布于 2020-08-28 19:41:42
您的html元素有两个相似的id。
<div>Check<input type="checkbox" id="**checkbox**"></div>
<button id="**checkbox**">Submit</button>
将一个更改为checkboxinput,另一个更改为checkboxbutton
发布于 2020-08-28 19:43:03
试试这个吧:
$(document).ready(function () {
//Try to add your event listener here
}
发布于 2020-08-28 19:58:34
简单地使用你的代码就可以了。确保在常规JS代码之前包含jQuery。在JSFiddle中尝试,除了CORS,没有得到任何$.ajax()错误,当然,因为我们不能访问路径( AJAX调用的URL)。
const checkbox = document.querySelector("#checkbox");
const button = document.querySelector("#button");
button.addEventListener("click", function(e){
var text = "";
if(checkbox.checked === true){
text = "Is Checked";
}
$.ajax({
url: '/update_if_checked/',
data: {'is_checked': text},
type: 'POST'
}).done(function(response){
console.log(response);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Check<input type="checkbox" id="checkbox"></div>
<button id="button">Submit</button>
https://stackoverflow.com/questions/63632723
复制相似问题