2013-05-11 32 views
-1

我想保存按鈕點擊文本框中的數據。我正在使用JQuery AJAX來執行此任務,如下所示。請注意,我在主題功能中製作了這個標籤。數據沒有得到保存使用JQuery.ajax

function theme_user_post_block($vars) 
{ 

$themeUserCommentInput =''; 

$themeUserCommentInput .= '<textarea id="txt_1"rows="1" cols="50"></textarea>'; 

$themeUserCommentInput .= '<input type="submit" value="Post Comment" align="center" 
class="btnPostComment" id="btn_1" />' 
return $themeUserCommentInput; 
} 

這能夠顯示我的文本框和按鈕裏面的頁面。現在,這裏是我的JS代碼: -

(function($) 
{ 
Drupal.behaviors.PostComment= { 

attach: function (context, settings) { 
    $('.btnPostComment', context).click(function (event) { 
    var post = "&newcomment=Comment1&logid=log1"; 
    jQuery.ajax({ 
       url: 'postcomment', 
       type: 'POST', 
       dataType: 'json', 
       data: post, 
       success: function (data) { alert(data); }, 
       error: function(jqXHR, textStatus, errorThrown){alert(textStatus + 
    errorThrown);} 
     });    
    }); 
    }      
    } 
    })(jQuery); 

接下來,我創建一個URL名稱的菜單頁如下: -

function postcomment_menu(){ 
$items=array(); 
    $items['postcomment']=array(
    'title'=>t(''), 
    'type'=> MENU_CALLBACK,  
    'page callback' => 'user_comment_post',   
    'access arguments' => array('access content'), 
); 
return $items; 
} 

function user_comment_post(){ 
global $user; 
$cid = db_insert('user_comment') 
    ->fields(array(  
    'comment_user_id' => $user->uid, 
    'reference_id' => $_POST['logid'],  
    'comment_desc'=>$_POST['newcomment'], 
    'createdon'=>REQUEST_TIME, 
    )) 
    ->execute(); 
    if($cid!=0) 
    { 
    //GetUserComments($i); 
    drupal_json_output("success"); 
    } 
} 

所以我這樣做所需的jQuery + Ajax的所有東西提交功能。當我按下「發表評論」按鈕時,它給我錯誤警報說「errorundefined」。該警報顯示爲jQuery.AJAX函數內部的錯誤結果。此外,自定義菜單回調也沒有被調用。

+0

您的示例代碼看起來不正確。即使從複製粘貼,請確保您顯示的代碼是有效的格式,否則我們不知道您是否有這個問題是因爲它。在這裏''textarea id =「txt_1'」rows =「1」cols =「50」>';''textarea'的'id'屬性'txt_1'中有一個額外的''' ',搞亂了格式。 – Nope 2013-05-11 15:54:48

+0

對不起,我的代碼錯誤。實際上,爲簡單起見,id中的動態值被靜態值替換。我編輯了編碼部分。 – user1843970 2013-05-11 18:25:29

回答

1

發佈數據作爲對象...,並確保你的帖子的網址是正確的.. URL不正確無誤

var post = {newcomment: 'Comment1',logid:'log1'}; 
+0

我改變了後面提到的發佈對象,但它也沒有工作,並顯示我警告box.Please錯誤,請讓我知道爲什麼後url不正確,應該在actual.I忘記聲明$ user user_comment_post全局(),但它在實際的代碼中存在。請不要將其視爲丟失。 – user1843970 2013-05-11 18:03:51

+0

url是您在服務器中調用的頁面或函數的路徑....「postcomment」會將您帶到serverside函數中。 – bipen 2013-05-11 18:14:36

+0

postcomment是URL的路徑。你想說我需要傳遞函數名稱而不是URL嗎? – user1843970 2013-05-11 18:30:59

0

我來結束這個問題。我不知道什麼可能是解決方案或根本原因,但我最終解決了這個問題。我微不足道地在我的jQuery.ajax函數中添加一行(async:false),並且一切正常。請參閱下面的代碼:

jQuery.ajax({ 網址: 'postcomment', 類型: 'POST', 數據類型: 'JSON', 異步:假, 數據:職務, 成功:功能(數據){ 警報(數據); }, 錯誤:功能(jqXHR,textStatus,errorThrown){ 警報(textStatus + errorThrown); } });

如果有人知道這條線會做什麼,請與我們分享。