这里我想用一些参数来调用php函数,这个参数将保存在一些jquery函数中。
我有php函数,它接受一个参数并执行sql查询。 而且我有一个jquery函数,当我从下拉框中选择项目时,我得到不同的值。
现在我想将下拉框的值传递给php函数,我该怎么做? 这就是我所做的
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
// here i want to pass this variable value to php function
});
php
function productManagement($procat){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_name,product_category,product_image_url FROM product_list where product_category='$procat'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["product_name"]."</td><td><a href=''><span class='glyphicon glyphicon-remove'></span>Remove</a></td><td><a href='edit-product.php'><span class='glyphicon glyphicon-edit'></span>Edit</a></td></tr>";
}
} else {
echo "No results found";
}
$conn->close();
}
我该怎么做?
答案 0 :(得分:3)
另一种方法是使用Ajax,如:
Jquery代码:
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
// here i want to pass this variable value to php function
-----------------------------------------------------
$.ajax({
url: 'newFunctionFile.php',
type: 'POST',
data: 'category='+category,
success: function(data) {
//you can add the code to show success message
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
});
并且你必须为php函数创建一个文件,假设文件名是newFunctionFile.php,正如我在ajax调用中提到的那样:
if(isset($_POST['category'])) {
productManagement($_POST['category']);
}
function productManagement($procat){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_name,product_category,product_image_url FROM product_list where product_category='$procat'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["product_name"]."</td><td><a href=''><span class='glyphicon glyphicon-remove'></span>Remove</a></td><td><a href='edit-product.php'><span class='glyphicon glyphicon-edit'></span>Edit</a></td></tr>";
}
} else {
echo "No results found";
}
$conn->close();
}
答案 1 :(得分:1)
这些方面的内容如何。
在你的javascript中:
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
location.href = location.href + "?val="+category; //reload the page with a parameter
});
然后在PHP中,将此代码添加为函数调用
if(isset($_GET['val'])) { //if 'val' parameter is set (i.e. is in the url)
productManagement($_GET['val']); //call function, with that parameter
}