尝试用PHP代码建立一个包含添加产品功能的网站。假设我们要添加手机产品,类别将是手机,子类别可以是三星或 iPhone。另一个例子是汽车——特斯拉或丰田。面临的问题是,当我选择类别后,该类别的子类别选项无法像实时一样立即刷新。获取子类别选项的方法是从类别表中SEARCH ALL并获取具有相同SELECTED类别ID的子类别。但是当我更改类别ID的值时,子类别选项无法刷新,因为php是服务器端代码。我确实尝试过 ajax 和 URL 参数,但这已经在表单内,这两种方式需要 GET 和 POST,我不认为嵌套这两种表单是一个好主意。 Cookie 仅在我重新加载页面后才起作用,以便 php 代码可以捕获 cookie 值。(或者它可以,但我完全是 cookie 的新手,所以我不知道)。还有其他办法吗?
php
$x = $_COOKIE['scid'];
$c = getByID("scategory",$x);
脚本
$('.categoryid').change(function(){
$('#tajax').click(function(){
var q = $('.categoryid').val();
console.log(q);
window.history.replaceState(null, null, "?cid="+q);
document.cookie = "scid="+q;
});
});
你可以这样做。
首先,在前端中,将
change
事件侦听器更改为 #categoryid
。下面是一个建议(我使用的是查询参数,而不是 cookie)。
$('.categoryid').on('change',function() {
let catId = $(this).val();
let subcategory = $('.scid');
let options = '';
$.ajax({
url: 'your-subcategory-script.php',
data: {'cat':catId},
type: 'POST',
dataType: 'json', // expected response is in json format
beforeSend: function() {
// whatever you need to do
// before the ajax - disable a btn, etc
// you can omit this entire part
// if you don't need to do anything
},
success: function(data) {
if(data.error) {
alert(data.message);
} else {
// we're clearing the current subcategories
subcategory.html('');
// our options - subcategories - are within data.message
// e.g data.message = [{1:"tesla",15:"samsung",....}]
$.each(data.message, function(key,value){
options += `<option value="${key}">${value}</option>`;
});
subcategory.append(options);
}
},
error: function(desc,err) {
alert(`Error: ${JSON.stringify(err)}, desc: ${JSON.stringify(desc)}`);
}
});
});
然后,在您的后端 -
your-subcategory-script.php
- 执行如下操作。
<?php
// Include your DB connection file, and your functions
include 'your-connection.php';
include 'your-functions-file.php';
/*
Optional verification with cookies, etc
to prevent the script from being called
by unauthorized users should be placed
here. I'll leave this part to you
*/
// I'm doing this because the ID should be a positive integer
$catId = isset($_POST['catId']) ? (int)$_POST['catId'] : 0;
if($catId < 1) {
// notify the user about the error - this could be a function as it will
// be used later on
echo json_encode(['error' => true, 'message' => 'Invalid category!']);
die();
}
// I'm using your function, BUT, please consider
// using prepared queries, to avoid SQL injection
$subcategories = getByID('subcategories',$catId);
// Did the query fail?
if(!$subcategories) {
echo json_encode(['error' => true, 'message' => 'Error retrieving subcategories!']);
die();
}
// Are there no results?
if(mysqli_num_rows($subcategories)) {
echo json_encode(['error' => true, 'message' => 'No subcategories found!']);
die();
}
$results = [];
foreach($subcategories as $row) {
$id = $row['id'];
$type = $row['type'];
$results[$id] = $type;
}
// I'm using just one flag for the JSON
// more here (section flags): https://www.php.net/manual/en/function.json-encode.php
echo json_encode(["error" => false, "message" => $results],JSON_UNESCAPED_UNICODE);
?>