我在运行时使用jQuery创建了一个div注释,并希望将这些注释保存在数据库中,以便注释在页面重新加载后显示日期。
我知道我应该在ajax请求中发送它,但不知道如何,任何帮助?
$('body').append('<div class="chat-container"><textarea class="chat-textbox" placeholder="Start a discussion here..."></textarea><input type="submit" class="chat-send" value="Send" /></div><div class="chat-content"></div>');
$('.chat-send').attr('disabled', true);
$('input[type="text"],textarea').on('keyup',function() {
var textarea_value = $(".chat-textbox").val();
if(textarea_value == '') {
$(".chat-send").click(function(){
var newComment = ($('.chat-textbox').val())
var newDate= ($.datepicker.formatDate('dd / mm / yy', new Date()));
$('.chat-content').append('<div class="new-comment"><label class="currentDate"></label>'+newComment+'</div>');
$('.currentDate').text(newDate);
$('.chat-textbox').val('');`enter code here`
$('.chat-send').attr('disabled', true);
});
您只需向您发送json数据以及您的ajax请求即可。你可以这样做。
var arr = { message: 'Hello mate', date: '21233244223', user_id: 234};
$.ajax({
url: '<your_api_url_here>',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
要以json的形式发送数据,您可以使用ajax post
。在chat-send
类的click处理程序中添加此内容:
$(".chat-send").click(function() {
......
var comment = {
"date": newDate,
"comment": newComment
};
// your post url here
var post_url = ....;
$.ajax({
type: "POST",
url: post_url,
data: JSON.stringify(comment),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
failure: function(error) {
alert(error);
}
});
});