Всем добрый вечер, как в этом коде можно реализовать обновление или перезагрузку только div`a с сообщениями? PHP: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Чат</title> <link rel="stylesheet" href="css/general.css" type="text/css" media="screen" /> </head> <body> <h2 style="font-size:14px; color:#666; text-align:center; margin:20px; font-weight:700"> Мини-чат</h2> <form method="post" id="form"> <table> <tr> <td><label>Ваше имя</label></td> <td><input class="text user" id="nick" type="text" MAXLENGTH="25" /></td> </tr> <tr> <td><label>Сообщение</label></td> <td><input class="text" id="message" type="text" MAXLENGTH="255" /></td> </tr> <tr> <td></td> <td><input id="send" type="submit" value="Отправить" /></td> </tr> </table> </form> <div id="container"> <div class="content"> <h1>Последние сообщения</h1> <div id="loading"><img src="css/images/loading.gif" alt="Загрузка..." /></div> <p> </div> </div> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="shoutbox.js"></script> </body> </html> обновлять или перезагружать нужно только <div id="container"> JS: PHP: $(document).ready(function(){ //global vars var inputUser = $("#nick"); var inputMessage = $("#message"); var loading = $("#loading"); var messageList = $(".content > p"); //functions function updateShoutbox(){ //just for the fade effect messageList.hide(); loading.fadeIn(); //send the post to shoutbox.php $.ajax({ type: "POST", url: "shoutbox.php", data: "action=update", complete: function(data){ loading.fadeOut(); messageList.html(data.responseText); messageList.fadeIn("fast"); } }); } //check if all fields are filled function checkForm(){ if(inputUser.attr("value") && inputMessage.attr("value")) return true; else return false; } //Load for the first time the shoutbox data updateShoutbox(); //on submit event $("#form").submit(function(){ if(checkForm()){ var nick = inputUser.attr("value"); var message = inputMessage.attr("value"); //we deactivate submit button while sending $("#send").attr({ disabled:true, value:"Отправляю..." }); $("#send").blur(); //send the post to shoutbox.php $.ajax({ type: "POST", url: "shoutbox.php", data: "action=insert&nick=" + nick + "&message=" + message, complete: function(data){ messageList.html(data.responseText); updateShoutbox(); //reactivate the send button $("#send").attr({ disabled:false, value:"Отправить" }); } }); } else alert("Пожалуйста, укажите имя и напишите сообщение"); //we prevent the refresh of the page after submitting the form return false; }); });
а в js это можно прописать, здесь есть параметр updateShoutbox - там написанно обновить по нажатию кнопки отправить. можно ли прописать что бы что обновление с интервалом 15 секунд было помимо нажатия кнопки отправить ? вариант с обновлением всей страницы не подходит, так как при этом сбросятся данные введеные в поле имя и сообщение
http://ruseller.com/lessons.php?rub=37&id=183 реализовал так, пока работает, проверяю: вот коды : в html странице подключаем: <script type="text/javascript" src="jquery.timers.js"></script> jquery.timers.js: PHP: jQuery.fn.extend({ everyTime: function(interval, label, fn, times, belay) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, times, belay); }); }, oneTime: function(interval, label, fn) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, 1); }); }, stopTime: function(label, fn) { return this.each(function() { jQuery.timer.remove(this, label, fn); }); } }); jQuery.extend({ timer: { guid: 1, global: {}, regex: /^([0-9]+)\s*(.*s)?$/, powers: { // Yeah this is major overkill... 'ms': 1, 'cs': 10, 'ds': 100, 's': 1000, 'das': 10000, 'hs': 100000, 'ks': 1000000 }, timeParse: function(value) { if (value == undefined || value == null) return null; var result = this.regex.exec(jQuery.trim(value.toString())); if (result[2]) { var num = parseInt(result[1], 10); var mult = this.powers[result[2]] || 1; return num * mult; } else { return value; } }, add: function(element, interval, label, fn, times, belay) { var counter = 0; if (jQuery.isFunction(label)) { if (!times) times = fn; fn = label; label = interval; } interval = jQuery.timer.timeParse(interval); if (typeof interval != 'number' || isNaN(interval) || interval <= 0) return; if (times && times.constructor != Number) { belay = !!times; times = 0; } times = times || 0; belay = belay || false; if (!element.$timers) element.$timers = {}; if (!element.$timers[label]) element.$timers[label] = {}; fn.$timerID = fn.$timerID || this.guid++; var handler = function() { if (belay && this.inProgress) return; this.inProgress = true; if ((++counter > times && times !== 0) || fn.call(element, counter) === false) jQuery.timer.remove(element, label, fn); this.inProgress = false; }; handler.$timerID = fn.$timerID; if (!element.$timers[label][fn.$timerID]) element.$timers[label][fn.$timerID] = window.setInterval(handler,interval); if ( !this.global[label] ) this.global[label] = []; this.global[label].push( element ); }, remove: function(element, label, fn) { var timers = element.$timers, ret; if ( timers ) { if (!label) { for ( label in timers ) this.remove(element, label, fn); } else if ( timers[label] ) { if ( fn ) { if ( fn.$timerID ) { window.clearInterval(timers[label][fn.$timerID]); delete timers[label][fn.$timerID]; } } else { for ( var fn in timers[label] ) { window.clearInterval(timers[label][fn]); delete timers[label][fn]; } } for ( ret in timers[label] ) break; if ( !ret ) { ret = null; delete timers[label]; } } for ( ret in timers ) break; if ( !ret ) element.$timers = null; } } } }); if (jQuery.browser.msie) jQuery(window).one("unload", function() { var global = jQuery.timer.global; for ( var label in global ) { var els = global[label], i = els.length; while ( --i ) jQuery.timer.remove(els[i], label); } }); в shoutbox.js: PHP: $(document).ready(function(){ //global vars var inputUser = $("#nick"); var inputMessage = $("#message"); var loading = $("#loading"); var messageList = $(".content > p"); //functions function updateShoutbox(){ //just for the fade effect messageList.hide(); loading.fadeIn(); //send the post to shoutbox.php $.ajax({ type: "POST", url: "shoutbox.php", data: "action=update", complete: function(data){ loading.fadeOut(); messageList.html(data.responseText); messageList.fadeIn("fast"); } }); } $(".content > p").everyTime(5000, function() { $.ajax({ type: "POST", url: "shoutbox.php", data: "action=update", complete: function(data){ loading.fadeOut(); messageList.html(data.responseText); messageList.fadeIn("fast"); } }); }); //check if all fields are filled function checkForm(){ if(inputUser.attr("value") && inputMessage.attr("value")) return true; else return false; } //Load for the first time the shoutbox data updateShoutbox(); //on submit event $("#form").submit(function(){ if(checkForm()){ var nick = inputUser.attr("value"); var message = inputMessage.attr("value"); //we deactivate submit button while sending $("#send").attr({ disabled:true, value:"Отправляю..." }); $("#send").blur(); //send the post to shoutbox.php $.ajax({ type: "POST", url: "shoutbox.php", data: "action=insert&nick=" + nick + "&message=" + message, complete: function(data){ messageList.html(data.responseText); updateShoutbox(); //reactivate the send button $("#send").attr({ disabled:false, value:"Отправить" }); } }); } else alert("Пожалуйста, представьтесь и напишите сообщение"); //we prevent the refresh of the page after submitting the form return false; }); }); тут добавлены: PHP: $(".content > p").everyTime(30000, function() { $.ajax({ type: "POST", url: "shoutbox.php", data: "action=update", complete: function(data){ loading.fadeOut(); messageList.html(data.responseText); messageList.fadeIn("fast"); } }); });
Проверил, работает во всех браузерах: на ie 7 и (chrome, safari, firefox, opera - эти все новые версии)