在java脚本中获取ajax响应时出错

时间:2016-09-07 10:16:39

标签: javascript php ajax codeigniter

在我的项目中使用ajax发送消息问题是我无法在ajax函数中得到响应,此函数之前完美运行,无法找到问题的确切原因帮我解决问题

AJAX

var str = {
  message:message, department_id:department, email:email, username:name
};

$.ajax( {
  type: "POST",
  url:'<?php echo base_url(); ?>home/savemessage',
  dataType:"json",
  data: str,
  success: function(msg) {
    $('#sentchat') . hide();
    $('#chatmessage') . show();

    $('#userchat') . html(msg . dataid);
    $('.chat-box-content') . hide();

    $('#adminname span').html('waiting for admins reply');

    var elem = document . getElementById('userchat');
    elem.scrollTop = elem . scrollHeight;
  }
});

php控制器

function savemessage() {

  extract($this->input->post());



  $data['message_id'] = $this->session->userdata('msgid');
  $data['username'] = $username;
  $data['email'] = $email;
  $data['department_id'] = $department_id;
  $data['message'] = $message;
  $data['datetime'] = date('Y-m-d H:i:s');


  $data['status'] = 'new';
  $data['message_by'] = '1';
  $this->db->insert('message', $data);

  echo json_encode($username);
  exit;
}

我无法得到答案,帮助我解决它

1 个答案:

答案 0 :(得分:0)

您使用ajax与PHP脚本进行通信,在PHP脚本中您可以拥有要执行的函数的内容。例如,在您的代码中:

$.ajax( {
  type: "POST",
  url:'<?php echo base_url(); ?>home/savemessage.php',
  dataType:"json",
  data: {myData:str},
  success: function(msg) {
    $('#sentchat') . hide();
    $('#chatmessage') . show();

    $('#userchat') . html(msg . dataid);
    $('.chat-box-content') . hide();

    $('#adminname span').html('waiting for admins reply');

    var elem = document . getElementById('userchat');
    elem.scrollTop = elem . scrollHeight;
  }
});

然后,在服务器端php脚本&#34; savemessage.php&#34;会收到POST动作,所以你可以:

if(isset($_POST['myData']) && !empty($_POST['myData'])) {
  $obj = $_POST['myData'];
  //rest of your code

  echo json_encode($username);
  exit;
}

但是,从您的代码中我看不到定义的$ username,因此可能会返回错误。