gpt4 book ai didi

php - 如何在不重新加载页面的情况下更新 mysql 数据库

转载 作者:行者123 更新时间:2023-11-29 01:12:26 25 4
gpt4 key购买 nike

感谢观看。我有一个很长的项目列表,用户单击图像(加号)将项目添加到他们的个人列表中。在他们点击 + 的那一刻,它加载了一个“add-item.php?itemid=*”,它处理下面的代码,然后将它们重定向到他们自己的列表,我确实让它重定向回全局列表,但后来不清楚如果该项目已添加到他们的列表中,则给用户。我将如何在不去任何地方的情况下全部更新数据库,我正在考虑 javascript 但从未写过任何东西。任何帮助都会很棒! :)

<?php 
ini_set('display_errors', 'On');
error_reporting(E_ALL);

$bucketlist=MYSQL_QUERY( "SELECT * FROM membersbuckets where userid = $userid AND bucketid = $bucketid")
or die(mysql_error());

$bucketlist=mysql_fetch_array( $bucketlist ) ;

if($bucketlist < 1) {

mysql_query("INSERT INTO membersbuckets (memberbucketid, userid, bucketid, complete)
VALUES ('', '$userid', '$bucketid', '0')");
echo "Adding item to your bucketlist...";
echo "<meta http-equiv='Refresh' content='2; URL=mybucketlist.php'/>";
}
else {
echo "This item is already on your list, redirecting you to your list";
echo "<meta http-equiv='Refresh' content='2; URL=mybucketlist.php'/>";
}
?>

提前致谢! :)

最佳答案

正如每个人所说,您需要 AJAX。

由于您从未编写过任何 javascript,因此这里有一份指南。

代替你的

<a href="add-item.php?itemid='.$itemId.'" > Add Item </a>

<a onclick="addItemToUsersList('.$itemId.')" > Add </a>

对于 AJAX,请按照 Angelo 的建议使用 jquery。下载它并添加以下内容

<script type="text/javascript" src="http://path/to/jquery-latest.min.js"></script>
<script type="text/javasript">
function addItemToUsersList(itemId)
{
$.ajax({
'url': 'path/to/add-item.php',
'type': 'GET',
'dataType': 'json',
'data': {itemid: itemId},
'success': function(data)
{
if(data.status)
{
if(data.added)
{
$("span#success"+itemId).attr("innerHTML","Item added to your personal list");
}
else
{
$("span#success"+itemId).attr("innerHTML","This item is already on your list");
}
}
},
'beforeSend': function()
{
$("span#success"+itemId).attr("innerHTML","Adding item to your bucketlist...");
},
'error': function(data)
{
// this is what happens if the request fails.
$("span#success"+itemId).attr("innerHTML","An error occureed");
}
});
}
</script>

最后,在您的 path/to/add-item.php 文件中编写添加项目的代码。参数 itemId 将在此处作为 $_GET['itemId']​​ 提供。只需使用 json_encode 返回正确的状态值。

if($bucketlist < 1) 
{
mysql_query("INSERT INTO membersbuckets (memberbucketid, userid, bucketid, complete) VALUES ('', '$userid', '$_GET['itemId]', '0')");
return json_encode(array("status" => true, "added" => true));
}
else
{
return json_encode(array("status" => true, "added" => false));
}

关于php - 如何在不重新加载页面的情况下更新 mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3630042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com