Localstorage to PHP variable

那年仲夏 提交于 2021-01-29 07:40:55

问题


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);
    }  
});

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);
?>

回答1:


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

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;
?>

You Should also cast user_id as an (int) if user_id need to be a single value and int

$verdier = (int) $user_id;


来源:https://stackoverflow.com/questions/30163855/localstorage-to-php-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!