我试图用ajax和PHP创建简单的聊天。从现在开始,当我试图在我的HTML中显示它时,我遇到了一个问题。
[
{"id_chat":1,"username":"admin","message":"ae","createddate":"2016-07-25"},
{"id_chat":2,"username":"admin","message":"aeaee","createddate":"2016-07-25"}
]
这是我的剧本
function buka_pesan()
{
var username = '<?=$this->input->cookie('cookie_webstore_user')?>';
$.ajax({
url: '<?=base_url();?>chat/show_chat',
success: function(data) {
$.each(data.data, function(k, v) {
$(".direct_add").append("<div class='direct-chat-msg right'> " +
"<div class='direct-chat-info clearfix'>" +
"<span class='direct-chat-name pull-left'>" + data.username + "</span>" +
"<span class='direct-chat-timestamp pull-right'>" + data.createddate + "</span>" +
"</div>" +
"<div class='direct-chat-text'> "+
data.message+
"</div>"+
"</div>");
});
}
});
}
$(window).load(function() {
buka_pesan();
var username = '<?=$this->input->cookie('cookie_webstore_user')?>';
$("#send_msg").click(function(){
if($("#pesannya").val() == '')
{
alert('Isi pesannya dulu kak');
}else
{
$.ajax({
url: '<?=base_url();?>chat/savechat',
data: {pesannya:$("#pesannya").val()},
type: 'POST',
dataType: 'JSON',
success: function(data) {
buka_pesan();
}
});
}
});
});
这是我的表格
<div class="direct-chat-messages">
<div class="direct_add"> </div>
<div class="box-footer">
<form action="#" id="form_id" method="post">
<div class="col-sm-5"> <div class="input-group">
<input type="text" id="pesannya" name="pesan" class="form-control">
<span class="input-group-btn">
<button type="button" id="send_msg" onclick="buka_pesan();" class="btn btn-warning btn-flat">Send</button>
</span>
</div>
</div>
</form>
</div>
<!-- /.box-footer-->
</div>
所以,我想展示最近的聊天。但没有帮助。用我上面的脚本我只能看到提交按钮。任何解决方案?
答案 0 :(得分:2)
使用data
v
$.each(data, function(k, v) {
$(".direct_add").append("<div class='direct-chat-msg right'> " +
"<div class='direct-chat-info clearfix'>" +
"<span class='direct-chat-name pull-left'>" + v.username + "</span>" +
"<span class='direct-chat-timestamp pull-right'>" + v.createddate + "</span>" +
"</div>" +
"<div class='direct-chat-text'> " +
v.message +
"</div>" +
"</div>");
});