2014-02-06 63 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

他们没有忘记加上它,整个问题是“它应该是什么?” –