单击jquery按钮+发送没有表单的数据 – 书签

我正在开发书签function,用户点击jQueryui按钮,然后将某些信息发送到数据库。 但我没有使用表单,因为没有用户输入的信息。

我从会话数据中提取用户的ID,我正在发送一个URI段(URL的一部分)

使用codeigniter / php。

我正在试图弄清楚要放在ajax / post函数的数据部分中的内容,因为没有输入表格/没有数据,以及如何处理控制器的“提交”部分。

调节器

function addBookmark(){ if ($this->input->post('submit')) { $id = $this->session->userdata('id'); $bookmark = $this->uri->segment(3, 0); $this->bookmarks_model->postBookmark($id, $bookmark); } } 

模型

 function postBookmark() { $data = array( 'user_id' => $user_id, 'bookmark_id' => $bookmark, ); $this->db->insert('bookmarks', $data); } 

HTML

  

jQuery的

 $('.somebutton').click(function() { $.ajax({ url: 'controller/addBookmark', type: 'POST', data: ???, success: function (result) { alert("Your bookmark has been saved"); } }); }); 

您的问题是您正在检查POST参数中的submit密钥。 您可以通过发送data: {submit:true}伪造它data: {submit:true}或删除if语句并只处理POST请求

 $('.somebutton').click(function() { $.ajax({ url: 'controller/addBookmark', type: 'POST', data: {'submit':true}, // An object with the key 'submit' and value 'true; success: function (result) { alert("Your bookmark has been saved"); } }); }); 

而不是使用.ajax()使用.get().post()

使用.get()

  $.get('controller/addBookmark',function(data){ alert('Your bookmark has been saved'); }); 

使用.post()

  $.post('controller/addBookmark', function(data) { alert('Your bookmark has been saved, The contents of the page were:' + data); }); 

来自jQuery.ajax()的文档

要发送到服务器的数据。 如果不是字符串,它将转换为查询字符串。 它附加到GET请求的URL。

如果您不知道要为数据添加什么,可能您应该删除该选项? 在控制器函数addBookmark()中,您可以通过删除if检查来减少代码。 试试这个,看看它是否适合你。