Javascript 如何使用ajax将本地存储数据发送到php页面?
我已经将表单数据存储在本地存储阵列中,我想用ajax将该阵列发送到php页面,还想访问php页面中的数据。Javascript 如何使用ajax将本地存储数据发送到php页面?,javascript,local-storage,Javascript,Local Storage,我已经将表单数据存储在本地存储阵列中,我想用ajax将该阵列发送到php页面,还想访问php页面中的数据。 这是我的密码- var myvalue=document.getElementById('name').value; var favorites_str = localStorage.getItem('my_favorites'); if(favorites_str == nul
这是我的密码-
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);
}
});
}
谢谢。假设您将数据存储在本地存储器中,并使用键名:“name”,您可以像下面这样获取数据,并将其发送到ajax调用中
data: {name: localStorage.getItem('name')}
假设您将数据存储在本地存储器中,密钥名为:“name”,您可以像下面这样获取数据并将其发送到ajax调用中
data: {name: localStorage.getItem('name')}
我在代码中看到的问题是,您试图在ajax请求中发送一个变量(
my_items
),但该变量是在不同的范围中定义的
请尝试以下方法:
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);
}
});
}
现在,
myu items
对象将可以在ajax请求中访问。我在代码中看到的问题是,您试图在ajax请求中发送一个变量(myu items
),但该变量是在不同的范围中定义的
请尝试以下方法:
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);
}
});
}
现在可以在ajax请求中访问
my\u items
对象。我已经编辑了代码。我忘了添加ajax代码。为什么不将JSON数组转换为字符串并发送到php,然后使用JSON\u decode()
读取它呢?我已经编辑了我的代码。我忘了添加ajax代码。为什么不将JSON数组转换成字符串并发送到php,然后使用JSON\u decode()
读取它呢?我不知道你是如何回答这个问题的,我只是暗示他如何在ajax调用中传递数据。我不知道你是如何回答这个问题的,我只是暗示他如何在ajax调用中传递数据。