[英]Retrieving each variable posted by AJAX
我將checkbox
選擇存儲在一個數組中,然后拆分每個數組並使用AJAX發布它們,以便我的PHP
函數可以使用發布的id/ids
來查詢我的MySQL
數據庫。
我的JavaScript的第一部分
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
alert(tbl);
第一部分按預期方式工作,每當我單擊一個checkbox
,都會提醒該值。
AJAX發布
$.ajax({
type: "POST",
url: "index.php",
data: "tbl=" + tbl
});
});
最后我的PHP
function describeTables() {
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}}
即使我只選擇一個選項,我也沒有得到tbl
。 為什么是這樣????
編輯我的復選框
function showTables() {
if (isset ( $_GET ['db'] )) {
$db = $_GET ['db'];
$link = mysqli_connect ( 'localhost', 'root', '', $db );
$qry = "SHOW tables";
$tbl_list = mysqli_query ( $link, $qry );
echo '<ul>';
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
echo '<input type="checkbox" name="tbl[]" class="tbl_list" value="' . $row [0] . '" class="tablebox" />';
echo $row [0];
echo '<br>';
}
}
}
showTables ();
第二編輯
提出建議后,我修改了代碼,但現在遇到了一個新問題,即頁面無法加載#dbdisplay
以下是我的完整JS代碼
if (!location.search.match(/db=[^&#]+/i)) {
$("#dbdisplay").show();
} else {
$("#qryDisplay").show();
}
$(document).on("change", ".checkbox", function () {
var db = $(this).val();
window.sessionStorage.setItem("db", db);
window.location.assign("index.php?db=" + db);
$("#dbdisplay").hide();
});
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
//alert(tbl);
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl': tbl }
});
});
舊功能
/*
$(document).on("change", ".tablebox", function () {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
var yourDB = window.sessionStorage.getItem("db");
window.location.assign("index.php?db=" + yourDB + '&tbl=' + tbl);
});
*/
我該如何解決??
在ajax調用中,數據必須是對象data: {'tbl': tbl}
您應該對數據使用“ {}”
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl' : tbl}
});
要么
$.ajax({
type: "POST",
url: "index.php&tbl="+tbl
});
Ajax調用的第一件事,數據必須是對象
data: {'tbl': tbl}
其次,Ajax無法直接調用php函數,因此您的index.php文件應該像這樣,沒有函數
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}
這應該工作
$.ajax({
type: "POST",
url: "someurl",
data: {"tbl=" + tbl}
});
http://api.jquery.com/jquery.getjson/
請參閱此處獲取文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.