【问题标题】:Input a value to database then automatically get the value without refreshing the page向数据库输入一个值,然后自动获取该值而不刷新页面
【发布时间】:2025-12-03 14:45:01
【问题描述】:

<form method="post">
<table cellpadding="0" cellspacing="0" border="1" class="display" id="example">
		<tr>
			<td><center>The Value</td>   
            <td><center>Choose Value</td>   
		</tr>

 
		<tr>
<?php
$result=mysql_query("SELECT * FROM  `mydatabase` ");
	while($row_array = mysql_fetch_array($result, MYSQL_ASSOC))
	{		
			$the_value= $row_array['db_value'];
    }

echo "<td>".$the_value."</td>";

?>
<td>
<input type="text" name="valuename">
<input type="submit" name="sub" value="Enter Value">
</td>
		</tr>
</table>
</form>

<?php
	if ( array_key_exists ( 'sub', $_POST )  ) 
	{

		$value_go_to_database=$_POST['valuename'];


$func=mysql_query(" INSERT INTO `db`.`mydatabase` (`db_value`) VALUES ('$value_go_to_database') ");

    }
?>

我的代码中的所有内容都很抱歉,如果此处缺少某些内容,我只想知道如何在不刷新/重新加载页面的情况下将值放入数据库,然后自动获取该值并将其放入我的桌子。 就像提交点击一样,它会自动将值/数据发送到我的数据库,然后 poof 也会在我的表中显示自己,而无需刷新/重新加载页面部分。 我是新手,不知道如何使用 AJAX 尝试阅读它有一段时间我不太明白如何将它插入到我的编码中。

提前致谢。

【问题讨论】:

  • 你应该使用 Ajax。在谷歌上搜索。
  • 如果以下任何答案都可以解决您的问题,请点击他们答案旁边的复选标记来接受他们的答案。这将有助于未来的用户搜索相同问题的答案。谢谢。

标签: jquery ajax refresh reload


【解决方案1】:

在 ajax 中发布值并获得响应。如果您已经在使用 jquery 库,请序列化表单数据并使用 $.post() 进行 ajax 提交或搜索如何使用 ajax 发布数据。

【讨论】:

    【解决方案2】:

    我了解第一次遇到 AJAX 时会感到困惑。虽然这是一个非常简单的概念,而且比它更繁琐。然而,这里有一个示例可以帮助您:

    我强烈建议使用 jQuery,因为它将所有这些函数包装成易于使用的语法。

    <form id="something">
        ...
    </form>
    
    <script type="text/javascript">
        $('form').click(function () {
            var values = $('form').serializeArray();
            $.ajax({url: 'http://yoururl.fake/somewhere.php', // The url to send the request to
                    type: 'POST', // This tells the AJAX function which type of request to send
                    data: values, // This is where you send your data to the server
                    success: function (data) {
                        // `data` now contains your response from the server. 
                        // It can be html, JSON, plain text, or whatever you choose.
                        // if `data` is html then you can simply insert it as such:
                        $('body').append(data); // Or wherever you want to put it.
                    },
                    error: function () {
                        // Something went wrong and here is your chance to nicely tell the user that.
                        alert('something went wrong');
                    }
            });
        });
    </script>
    

    【讨论】: