2016-10-24 36 views
0

我已經將表單數據存儲在本地存儲陣列中,並且我想用ajax將該數組發送到php頁面,並且還想訪問php頁面中的數據。
這裏是我的代碼 -如何使用ajax將本地存儲數據發送到php頁面?

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

感謝。

+0

我編輯了我的代碼。我忘記了添加ajax代碼。 – Deepak

+0

爲什麼不直接將JSON數組轉換爲字符串併發送給php並使用'json_decode()'來讀取? –

回答

0

假設您將數據存儲在本地存儲中,密鑰名稱爲「name」,您可以像下面那樣得到它,並且可以將它發送到ajax調用中。

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

我不明白你是如何回答 –

+0

的問題我只是想告訴他如何在ajax調用中傳遞數據。 –

0

,我可以在代碼中看到的問題是,你要發送的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); 
     } 
    }); 
} 

現在my_items對象將是Ajax請求的內部訪問。

相關問題