我对整个JavaScript和AJAX都很陌生。对于我的期末考试,我正在尝试创建一个Web应用程序。一个脚本将数据从用户发送到服务器并将其保存到textfile
,而另一个脚本始终向用户显示当前textfile
。
我得到了用户GUI上显示的文件的当前内容,我正在使用此ajax
函数:
var xmlHttp = createXmlHttpRequestObject();
//erstellen des Objektes, welches nachher mit der anderen Seite kommuniziert
function createXmlHttpRequestObject(){
var xmlHttp;
if (window.ActiveXObject) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if (!xmlHttp) {
alert("cant create that object");
}
else
return xmlHttp;
}
//jede sekunde wird der inhalt von send_note geladen
setInterval(function note(){
if (xmlHttp.readyState==0 || xmlHttp.readyState==4) {
xmlHttp.open("POST", "send_note.php?", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();
}
}, 500);
function handleServerResponse(){
if (xmlHttp.readyState==4) {
if (xmlHttp.status==200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("display").innerHTML = message;
setTimeout('note()', 1000);
}else{
alert('something went wrong');
}
}
}
note()
在加载用户的GUI正文时被调用。
我现在无法开展工作的两件事:
我呼叫note()
的段落如下所示:
<body onload="note()">
有人可以帮我吗?
答案 0 :(得分:0)
PHP必须回显ajax的任何输出才能读取它。通常它是JSON响应,在JS中你可以做function handleServerResponse(data) {JSON.decode(data);}
您正在将note
从函数覆盖到字符串。检查namings。
很少有笔记
使用匿名函数:setInterval(function () {});
您不需要setTimeout('note()', 1000);
,因为您的代码每500毫秒重复一次。
您是否考虑过使用jQuery ajax:
E.g:
$.ajax({
url: 'send_note.php',
type: 'POST',
dataType: 'json',
data: {id: 2}, //js object with data to send to server.
success: function (response) {
alert(data); //data will contain anything that server outputs in "send_note.php"
}
});
答案 1 :(得分:0)
您可以在setTimeout中定义函数注释()。我觉得把它定义在外面更好。
当你的函数si已经调用note时,不要声明var note。
如评论中所述,setTimeout应该是写入的setTimeout(注意,1000)
最后因为你使用了interval为什么要在同一个函数上使用setTimeout?是为了改变间隔持续时间吗?这不会像这样工作。您将在1秒后再次触发您的功能,而间隔将每500秒触发一次。