ajax函数未定义

ajax function not defined

本文关键字:未定义 函数 ajax      更新时间:2023-09-26

我对整个JavaScript和AJAX还很陌生。为了期末考试,我正在尝试创建一个网络应用程序。一个脚本将数据从用户发送到服务器,并将其保存到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');
		}
	}
}

CCD_ 4在加载用户所呈现的GUI的主体时被调用。

我现在无法工作的两件事:

  1. 如何使用我在这个ajax请求中使用的post变量将数据发送到响应的文件?我如何获取发送到该php文件中响应php文件的数据
  2. 谷歌chrome的开发工具向我显示了这个错误:Uncaught ReferenceError:note未定义

我调用note()的段落如下:

<body onload="note()">

有人能帮我吗?

在setTimeout中定义函数note()。我觉得最好在外面定义一下。

当您的函数已经调用了note时,不要声明var note。

正如评论中所说,应该写入setTimeout setTimeout(注意,1000)

最后,既然使用interval,为什么要在同一个函数上使用setTimeout?这是为了改变间隔时间吗?这样不行。您只需在1秒后再次触发您的函数,而间隔将每500秒触发一次。

  1. PHP必须回显任何输出以便ajax读取。通常是JSON响应,在JS中可以执行function handleServerResponse(data) {JSON.decode(data);}

  2. 您正在从函数到字符串重写note。检查命名。

少量钞票

  1. 使用匿名函数:setInterval(function () {});

  2. 您不需要setTimeout('note()', 1000);,因为您的代码将每500ms重复一次。

  3. 您是否考虑过使用jQuery ajax:

例如:

$.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"
    }
});