Please enable java script to visit.
NOTEBOOK
HOMEPHP / MySQLJS / HTMLWXappPythonC++Blender其他
jQuery 判断多个 checkbox 是否被激活,并使用 json 提交数组给 php 后端 - NOTEBOOK
jQuery 判断多个 checkbox 是否被激活,并使用 json 提交数组给 php 后端
PHP / MySQLJS / HTML
Posted on 2023-09-25
摘要 : 使用 $("#checkbox").is(":checked")。
这样在js提价表格数据时,先判断有没有勾选。
❱ 点击按钮时,将checkbox的状态添加到 POST 数据中。

$("#submit").click(function(){
var postdata = new formData();
if ($("#cleanloginr").is(":checked")) {
postdata.append("cleanloginr", $("#cleanloginr").val());
}
。。。。省略提交表格的代码
});




❱ 多个checkbox的判断是否勾选

❱ HTML 代码

<label><input type="checkbox" name="citys[]" value="广州"/>广州</lable>
<label><input type="checkbox" name="citys[]" value="深圳"/>深圳</lable>
<label><input type="checkbox" name="citys[]" value="上海"/>上海</lable>
<label><input type="checkbox" name="citys[]" value="苏州"/>苏州</lable>
<span id="submit">提交</span>

❱ js/jquery代码

<script type="text/javascript">
$(document).ready(function(){

$("#submit").click(function(){
var citys = []; // 定义空白数组
$("input:checkbox[name='citys[]']:checked").each(function(index,item){ // 遍历
citys.push(item.value); // 添加到数组尾部
});
citys = JSON.stringify(citys); // 转成 json

// 表格数据
var postdata = new formData();
postdata.append("citys", citys);

ajax_page(targeturl,postdata);// 自定义 提交function
});
});

function ajax_page(targeturl,postdata=null){
if(targeturl){
// ----------获取内容。
// var postdata = new formData();
// var xhr = null;
// postdata.append("doorKey","somePassword"); //带上 密码?
var result = $.ajax({
url: targeturl,
type: 'POST', // POST GET
data: postdata?postdata:null, // 提交post,若有
async:false, // true异步,false 同步:会等待结果再执行后面的。
// contentType:"multipart/form-data",
contentType: false,// 必须false才会自动加上正确的Content-Type
processData: false, // 不转换数据类型
timeout: 4000,
/* // 上传文件时的进度条,不能直接用,要编辑
xhr:function(){
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',function(e){
var loaded = e.loaded;// 已经上传大小情况
var tot = e.total;// 附件总大小
var per = Math.floor(100*loaded/tot).toFixed(2);
// console.log(i+': '+per+ '%');
// $('#bar_'+i).html(per + '%');
$('#bar_'+i).css({'width':per+'%'});
}, false); // for handling the progress of the upload
}
return myXhr;
},
beforeSend:function(){
// console.log(" 开始上传");
},*/
success:function(ajaxResult){
// console.log(ajaxResult);
return ajaxResult; // 返回给 ajax
},
error:function(ajaxResult){
//return ajaxResult; // 返回给 ajax
},
});
if(result.status==200){
return result.responseText;
}else if(result.status==404){
return "404 not found.";
}else{
return "Unable to reach the content, please try again. ("+ result.status + ")";
}
}
}
</script>

❱ php 后台代码

$citys = json_decode($_POST[''], true) ;