本地存储到PHP变量 [英] Localstorage to PHP variable

查看:55
本文介绍了本地存储到PHP变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过此Ajax调用发送和检索一些数据,并将结果保存在本地存储中,如下所示:

I am sending and retrieving some data with this ajax call and saving result in localstorage like this:

$.ajax({
    url: "list.php", 
    data: {values: values}, 
    dataType: "json",
    success: function(result){
    var dataToStore = JSON.stringify(result);
    localStorage.setItem('key', dataToStore);
    }  
});

然后,我在这样的单独的PHP文档中检索它,并尝试将其添加到PHP变量中.我认为发生此问题是因为当我console.log时,它记录了10次左右.而且我无法在PHP中回显它.如何正确通过?

Then I am retrieving it in a separate PHP document like this and trying to add it to a PHP variable. I think the problem occurs because when I console.log, it logs 10 times or so. And I can't echo it in PHP. How do I pass it correctly?

<script>
var localData = JSON.parse(localStorage.getItem('key'));

$.each(localData, function(key, value){
console.log("This is the data that is stored", localData)
$.ajax({
type: 'post',
        data: {localData}, 
        dataType: "json",
        success: function(result){
        console.log(result)
        }  

        });
</script>

<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = implode(", ", $user_id);
?>

推荐答案

您正在通过循环调用ajax()引起痛苦的异步功能真正的痛苦

You are causing an asynchronous functionality of ajax() real pain by calling it in a loop

为什么不像在php中那样使用 join()在js中使用," 来连接项目

Why dont you use join() to join items with ", " in js like what you do in php

<script>
var localData = JSON.parse(localStorage.getItem('key')).join(", ");


$.ajax({
type: 'post',
        data: {localData}, 
        dataType: "json",
        success: function(result){
        console.log(result)
        }  

        });
</script>

<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier =  $user_id;
?>

如果 user_id需要为单个值且int

$verdier = (int) $user_id;

这篇关于本地存储到PHP变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆