如何在php中使用localStorage和AJAX来更新我的数据库?

时间:2015-08-14 19:47:10

标签: php jquery ajax local-storage

我需要在PHP文件中使用 localStorage 值来更新数据库中的值。我知道我需要ajax来实现这一点,我无法让它发挥作用。

我的 localStorage 项目已命名为选项且存在(在浏览器中检查并将值存储在 div 中)

$(document).ready(function(){
        $.ajax({
            type: "POST",
            url: "activity.php",
            data: { storageValue: localStorage.getItem('option') },
            success: function(data){
                alert('success');
            }
        });
    });

PHP示例:

$option = $_POST['storageValue'];
mysql_query("...SET x = '".$option."'...");
echo 'Update complete';

我没有看到任何帖子数据,也没有收到回复。

谢谢!

1 个答案:

答案 0 :(得分:0)

您的信息页

<form>
<input type="hidden" value="thedatayouwanttopost" id="option"/>
</form>
<script src="Your_Js_File.js"></script>

您的JS文件:

document.getElementById('option').submit(); // This submits the form

var storageValue = $('#option').val(); // This gets the value of the form once it has been posted to the .php file

$(document).ready(function(){
        $.ajax({
            type: "POST",
            url: "activity.php",
            data: { storageValue:storageValue },
            success: function(data){
                alert('success');
            }
        });
    return false; // This stops the page from refreshing
    });

您的PHP文件将数据回调到AJAX并显示警报(activity.php):

...
$option = $_POST['storageValue']; // This is the post value of your hidden input on your page

mysql_query("...SET x = '".$option."'...");
?><input type="hidden" id="option" value="<?php echo $option; ?>"><?
// The input above posts the value of 'option' on your page back to your Ajax and spits out the request.
    ...