0

我从 w3school 阅读了一些关于 ajax 的教程。我假设服务器如何自动接收来自客户端的消息。我有两页,一页用于客户端,一页用于服务器。当有人键入内容并单击提交时,服务器页面将自动附加到屏幕上。这就是我使用的:

client:
<script>
$(function(){
$("#submit").click(function(){
$.post("server.html", $("#f1").value()+"&&"+$("#f2").value(), function(){
alert("send!");
});
});
});
</script>
<input type="number" name="f1" id="f1" placeholder="first number..." />
<input type="number" name="f2" id="f2" placeholder="second number..." />
<input type="submit" id="submit" value="submit" />

server:
$(function(){
$("#pmsg").hide();
$("#msg").load("client.html", function(){
$("#pmsg").show().delay(1000).hide();
});

});
<div id="pmsg">new message</div>
<div id="msg"></div>

I can't achieve the result that I want, could someone tell me how to fix it? thx!

I solved the problem. I use php to write the message into a txt file and then use $.get to get the message from that file.

4

1 回答 1

0

您基本上是在使用 jQuery 库及其加载函数来完成 ajax 工作。它实际上是这样工作的:它根据浏览器创建 http 对象(对于 IE - activexobject,FF - xmlhttprequest)并将请求发送到我们称为服务器站点的 url。有四种状态:

0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready 

下面是代码:

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
于 2013-06-17T10:57:00.367 回答