[英]Ajax Posting Form Elements
我需要你的帮助。
我试图用ajax“发布”表单元素。 当我按名称获取所有元素时,我会在浏览器的控制台上看到结果,并且还将数据发送到数据库。 但是问题是。 它发送错误的复选框值。 即使我没有检查,它也总是发送“ on”值。顺便说一句,选择零件正在正确地工作。
这是我的形式部分
<div class="right-side" id="right-side-id">
<form action="criterias.inc.php" id="ajax" method="POST" class="ajax">
<br>
<center>
<h>Customize Your Experience</h>
</center>
<div class="right-side-options">
People interested in Friendship<input type="checkbox" class="checkmark" name="friendshipcheck"><br>
People interested in Practice<input type="checkbox" class="checkmark" name="practicecheck"><br><br>
Subject of Conversation
<select name="subjectName" class="select">
<option value="science">Science</option>
<option value="love">Love</option>
<option value="depressive">Deppressive</option>
<option value="anything">Anything</option>
</select><br><br>
Language
<select name="languageName" class="select">
<?php
include('connection.php');
$sql = "SELECT* FROM languages";
$query = mysqli_query($conn, $sql);
while ($result = mysqli_fetch_assoc($query)) {
$language = $result["language_name"];
echo "<option>" . $language . "</option>";
}
?>
</select>
<input type="submit" class="searchbutton" id="search-button-id" value="Search" onclick="showPartner();">
</div>
</form>
</div>
这是我的Javascript代码。
$('form.ajax').on('submit',function(){
var that = $(this),
url=that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name=that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url:url,
type:type,
data:data,
success:function(response){
console.log(response);
}
});
return false;
});
问题是您正在尝试实现自己版本的serialize方法,如果未选中,则不包括复选框。 您的逻辑是无论是否包含字段,只要它们具有名称字段。
与其尝试编写自己的实现并重新发明轮子,不如使用jQuery已经实现的serialize()
方法。
$('form.ajax').on('submit', function (e) {
e.preventDefault();
var $this = $(this),
url = this.action,
type = this.method,
data = $this.serialize();
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
});
这是jQuery中的默认行为。 您需要做的是显式地处理复选框值,以确定是否已选中它。 如下更改ajax方法。 我们将修改循环,以便检查复选框值:
that.find('[name]').each(function(index, value){
var that = $(this),
name= that.attr('name'),
value = that.val();
if (that.attr('type') === 'checkbox') {
data[name] = that.is(':checked') // this will set the value to true or false
} else {
data[name] = value;
}
});
您应该使用;
$('#checkboxelement').is(":checked")
读取复选框和单选元素的选中状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.