2014-02-06 60 views
0

我試圖通過jQuery使用.ajax函數將2條信息保存到數據庫。我想在WordPress中保存postID和userID。我想我得到了大多數函數的jist,但需要弄清楚如何將數組發送到處理頁面,以便我可以插入它。這是我到目前爲止寫的:通過jQuery保存數據到數據庫.ajax

$(document).ready(function() { 
     $('#saveme').click(function() { 
      $.ajax({ 
      type: "POST", 
      url: "save_data.php", 
      contentType: "application/json; charset=utf-8", 
      data: "", 
      dataType: "json", 
      success: function (msg) { 
       alert("This recipe has been saved in your profile area!"); 
      } 

     }); 
    }); 

任何人都可以提供一些線索一個什麼進入的數據值來存儲2條信息,我可以發送給處理頁面?

我使用的PHP和代碼是在.js文件中,所以我可能還需要知道將信息發送到js文件。謝謝!!

+0

'數據: 「」,'是'空是data'在您將數據發送到'save_data.php' ajax'對象的'關鍵。 – user2727841

+0

數據關鍵字存儲的值將發送到其他頁面上的Ajax請求,你必須在var id ='2'中定義你的值並將其存儲在數據中:「id =」id; – user12

回答

1

釷要發送到服務器的數據類型是包含零個或多個鍵值對或字符串的JavaScript對象。對於你的情況

data: { 'postID' : $('#postID').val(), 'userID' : $(('#userID').val() },

+0

謝謝!我是否必須爲頁面上的postID和userID添加隱藏的輸入,以便我可以獲取這些內容? –

1

數據應該是包含要保存數據的JSON對象,即

$(document).ready(function() { 
     $('#saveme').click(function() { 
      $.ajax({ 
      type: "POST", 
      url: "save_data.php", 
      contentType: "application/json; charset=utf-8", 
      data: {postID: "A123456", userId: "HGSADKJ"}, 
      dataType: "json", 
      success: function (msg) { 
       alert("This recipe has been saved in your profile area!"); 
      } 

     }); 
    }); 
+0

沒有像「JSON對象」這樣的東西。你有JSON代表一個對象,但它是一個字符串。您在該代碼中設置爲「data」屬性的值是JavaScript對象。 –

+0

JSON不是任何方式的字符串。這是一個對象:'typeof {foo:'bar'} ==「object」' –

+0

不,這是不正確的。 JSON是JavaScript對象表示法;它是對象或數組的字符串表示形式。你剛剛描述的是一個** JavaScript對象**,而不是JSON。 –

0

只需創建一個JSON對象,並將其發送: (假設說有通過ID的頁面上的元素和帖子ID的用戶ID

var jsonData = { "postID" : $("#postID").val(), 
       "userID" : $(("#userID").va;() } 


$(document).ready(function() { 
     $('#saveme').click(function() { 
      $.ajax({ 
      type: "POST", 
      url: "save_data.php", 
      contentType: "application/json; charset=utf-8", 
      data: jsonData, 
      dataType: "json", 
      success: function (msg) { 
       alert("This recipe has been saved in your profile area!"); 
      } 

     }); 
    }); 
+0

沒有像「JSON對象」那樣的東西。 JavaScript有對象,JSON是可能代表一個字符串的字符串。 –

0

你忘了添加數據

$(document).ready(function() { 
    var postID='<?php the_id(); ?>'; 
    var userId='<?php author_id(); ?>'; 
     $('#saveme').click(function() { 
      $.ajax({ 
      type: "post", 
      url: "save_data.php", 
      contentType: "application/json; charset=utf-8", 
      data: {postID: postID, userId: userId}, 
      dataType: "json", 
      success: function (msg) { 
       alert("This recipe has been saved in your profile area!"); 
      } 

     }); 
    }); 
+0

他們沒有忘記加上它,整個問題是「它應該是什麼?」 –