我正在尝试使用ajax在wordpress数据库中插入所有已选中复选框的值。我有多个选择的问题。
答案 0 :(得分:0)
这是使用ajax输入复选框值的代码。希望你能找到答案。
<input id="" name="checkbox_id[]" type="checkbox" value="" > // Checkbox
$('#submitButton').click(function(){
var checkboxValue = new Array();
$.each($("input[name='checkbox_id[]']:checked"), function() { //Checkbox by its name
checkboxValue.push($(this).val());
// or you can do something to the actual checked checkboxes by working directly with 'this'
// something like $(this).hide() (only something useful, probably) :P
});
$.ajax({
type: "POST",
url: "submitUrl",
data: {'checkboxValue':checkboxValue},
success: function(data){
console.log(data);
}
});
});
答案 1 :(得分:0)
这是使用纯JavaScript的方法。
//add an eventListener to your submit button
document.getElementById( "submitBtn" ).addEventListener( "click", function( event ){
event.preventDefault(); //prevent default behavior of the submit button
//get values of only checked checkboxes and then push them onto an array
let checkboxArr = array();
let checkboxNodeList = document.querySelectorAll( "input[type=checkbox]:checked" );
for ( let i = 0; i < checkboxNodeList.length; i++ ) {
checkboxArr.push( checkboxNodeList.value );
}
//prepare array to be sent
checkboxArr = encodeURIComponent( JSON.stringify( checkboxArr ) );
//parameters to send in the request
let parameters = "action=your_php_function_name&checkboxArr=" + checkboxArr;
//then you would create an XHMLHttpRequest object and send the data
let xhr = new XMLHttpRequest();
//set request ( method, wordpress ajax_url, asynchronous )
xhr.open( "POST", your_wp_localize_script_variable.ajax_url, true );
//set request header to allow key/value pairs being sent via URL
xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded;" );
//on success
xhr.onload = function(){
//status OK
if ( this.status == 200 ) {
console.log( "response->" + JSON.parse( this.responseText );
}
}
//if an error occurs
xhr.onerror = function(){
console.log( this.responseText );
}
//send the request
xhr.send( parameters );
});
然后,在向您发送请求的函数的PHP端,您可以检索如下复选框值的数组。
//have to decode and strip slashes
$checkboxArr = json_decode( stripslashes( $_POST[ 'checkboxArr' ] ) );
然后您可以根据需要将数据写入数据库。
我希望您觉得这有用。