簡體   English   中英

如何在AJAX中使用php中的localStorage更新數據庫?

[英]How can I use localStorage in php with AJAX to update my database?

我需要在PHP文件中使用localStorage值來更新數據庫中的值。 我知道我需要ajax來實現這一點,但我無法使其正常工作。

我的localStorage項命名為option,並且存在(在瀏覽器中檢出並將值存儲在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';

我沒有看到任何帖子數據,也沒有得到回復。

謝謝!

您的頁面:

<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.
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM