duanlu5055 2013-08-05 10:20
浏览 47
已采纳

需要与ajax概念项目的想法

i've create a chat in ajax, but i still have some problem that i can't recognize. When the page is loaded, the php load all the opened chat and relative mex, then there's an addmex ajax function: when the user hits enter it's called passing this.value and the cod_chat. The ajax function send these data to the php, which insert them into the db and add the last mex into the chat. Every X seconds an update function is called, to update the chat. It all works until it gets to the addmex function: the php works, because it add the mex into the db, but for some reason it refresh the page. Could i use RTMP?

This is the code of the form:

<input type='text' class='chat_input' value='write something' onkeydown='if (event.keyCode == 13){addmex(this.value); this.value='';}'/>

and this is the code of the ajax function (don't worry about the php variables because this function is loaded by echo):

function addmex(mex)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","addmex.php?cod_contatto="+' . $cod_contatto . '+"&mex="+mex,false);
xmlhttp.send();
document.getElementById("messaggi_' . $cod_contatto . '").innerHTML+=xmlhttp.responseText;
}

I set Async as false because it respond slowly, and if i set true works only with some alert that let the server part complete. Any idea?

  • 写回答

3条回答 默认 最新

  • dpauf28808 2013-08-05 10:36
    关注

    How is your insert field implemented? If it is in a HTML form, it will send the form when you hit enter. So if this is given, you need to prevent the default enter action in order to prevent the page refresh: Just get the js event (onkeydown), do what you need to do and return false.

    EDIT

    You may assign the handler in a diffrent way: Give the input an ID so this will work:

    document.getElementById(yourID).onkeydown = function(event) {
      if(event.keyCode == 13){addmex(this.value); this.value='';}
      return false;
    }
    

    EDIT 2

    Your first code has a syntax error, it should be:

    .... this.value="";}'/></form>
    

    You cant use the same quotes in the inner String: '''' are like 2 strings, while '""' is one string in another.

    SOLUTION For those who happen to read this.

    The form tag was unnecessary and caused the page to refresh (sometimes preventing default does not work?!).

    Finally there was the refreshing via ajax missing. Just do a setInterval() with the function and it should work all fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作