【问题标题】:How can I use localStorage in php with AJAX to update my database?如何在 php 中使用 localStorage 和 AJAX 来更新我的数据库?
【发布时间】:2015-08-15 05:31:13
【问题描述】:

我需要在 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';

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

谢谢!

【问题讨论】:

  • 好像你的 JS 有错误。 data: {...} 部分中不能有 ; 字符。
  • ty,我删除了 ;但我的 php 文件仍然没有返回任何内容或显示警报:(

标签: php jquery ajax local-storage


【解决方案1】:

您的页面:

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

【讨论】:

  • 好的,谢谢,我认为输入应该触发我的警报?即使我将它添加到我的代码中,它仍然不返回任何内容或更新我的数据库。我仍然无法在浏览器中看到帖子数据。
  • 您要从中提取 $option 的 .php 文件是否称为“activity.php”?
  • 我已经更新了我的答案。如果它仍然不起作用,请告诉我。
  • 是的,我仔细检查了,执行我的 JS/Ajax 脚本的文件名为:localstorage.php,我在 ajax 脚本中调用的文件没有错字
  • 所以它是这样的:您希望在 上发出警报的页面,然后在 Ajax 中,url 是您所在的 .php 脚本从中提取 PHP?
猜你喜欢
  • 2010-10-25
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 2012-08-08
  • 2014-03-29
  • 1970-01-01
  • 2020-09-22
  • 2018-04-11
相关资源
最近更新 更多