使用JQuery.ajax无法保存数据

时间:2013-05-11 15:39:32

标签: json jquery drupal drupal-7

我想在按钮点击上保存文本框中的数据。我正在使用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;
}

这能够在页面内显示Textbox和Button。现在这是我的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 Name的菜单页面如下: -

 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 Submit功能所需的所有事情。当我按“发表评论”按钮时,它会在警报中显示错误“errorundefined”。警报显示jQuery.AJAX函数内部的错误。此外,自定义菜单回调也没有被调用。

2 个答案:

答案 0 :(得分:1)

将数据作为对象发布...并确保您的帖子网址正确..网址看起来不正确

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

答案 1 :(得分:0)

我结束了这个问题。我不知道决议或根本原因可能是什么,但我最终解决了这个问题。我在我的jQuery.ajax函数中添加了一行(async:false),一切都很完美。请参阅以下代码:

jQuery.ajax({           url:'postcomment',           类型:'POST',           dataType:'json',           async:false,           数据:帖子,           成功:函数(数据){             警报(数据);           },           错误:function(jqXHR,textStatus,errorThrown){             alert(textStatus + errorThrown);           }         });

如果有人知道这条线路的用途,请与我们分享。

相关问题