简体   繁体   English

如何使用ajax将本地存储数据发送到php页面?

[英]How to send local storage data with ajax to php page?

I have stored form data in local storage array and i want to send that array with ajax to php page and also want to access data in php page. 我已经将表单数据存储在本地存储数组中,并且我想将带有ajax的数组发送到php页面,并且还希望访问php页面中的数据。
Here is my code - 这是我的代码-

    var myvalue=document.getElementById('name').value;        
                    var favorites_str = localStorage.getItem('my_favorites');    
                    if(favorites_str == null) {    
                    favorites = [];      
                    favorites.push({ "name":myvalue});      
                    }    
         else{      
                    favorites = JSON.parse(favorites_str);      
                    favorites.push({ "name":myvalue});      
                    }  
             localStorage.setItem('my_favorites',JSON.stringify(favorites));      
    var data = localStorage.getItem('my_favorites');      
                    if(data == null){      
                    alert("0 favorites");      
                    }else{      
                    favorites = JSON.parse(data);      
                    $.each(favorites, function(index,item){      
                    var my_items=item.name;         
                    })      
                    };    
if(navigator.onLine)    
                 {  
                     $.ajax({  
                         url:'http://localhost/offline/nextpage.php',  
                         type:'post',  
                         data:{my_items:my_items},  
                         success:function(data)  
                         {  
                           $('#result').html(data);  
                         }  
                     });  
                 }

Thanks. 谢谢。

假设您将数据存储在本地存储中,键名称为:“ name”,则可以像下面那样进行获取并将其发送到ajax调用中。

data: {name: localStorage.getItem('name')}

The problem that I can see in your code is that you are trying to send a variable ( my_items ) at the ajax request but the variable is defined in a different scope. 我在您的代码中看到的问题是,您正在尝试在ajax请求中发送变量( my_items ),但是该变量是在其他作用域中定义的。

Try this instead: 尝试以下方法:

var myvalue=document.getElementById('name').value; 
...
favorites = JSON.parse(data);
var my_items = [];
$.each(favorites, function(index,item){
    my_items.push(item.name);
});

if(navigator.onLine) {
    $.ajax({
        url:'http://localhost/offline/nextpage.php',
        type:'post',
        data:{my_items:my_items},
        success:function(data)
        {
           $('#result').html(data);
         }
     });
 }

Now the my_items object is going to be accessible inside the ajax request. 现在,可以在ajax请求中访问my_items对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM