我正在开发一个应该通过 AJAX 与服务器交互的页面,但我对 AJAX 的经验极其有限。以下是该页面的工作方式。
单击该按钮时,如果单击“测试”单选按钮,则仅显示一个弹出窗口,说明输入有效。 单击按钮时,如果单击“live”单选按钮,则程序应该使用 URL“http://cs.sfasu.edu/rball/351/exam2.php”向服务器发送请求,输入框的内容是“name”的值范围。 然后,该页面将发送回一个 JSON 对象,我需要将其解析为常规变量。
我将保留其余 JSON 内容,因为这不是我要求的。
到目前为止,我已经完成了页面的设计,但就像我说的,我真的不知道我在用 AJAX 东西做什么。我为此编写了一些代码,但不确定它是否正确。
这是我的代码:
<html>
<head>
<title>anner, Taylor</title>
<style type = "text/css">
canvas {
border: 2px solid black;
}
</style>
<script type = "text/javascript">
window.onload = function() {
var TTcanvas = document.getElementById("myCanvas");
var TTcontext = TTcanvas.getContext("2d");
TTcontext.strokeStyle = "red";
TTcontext.fillStyle = "red";
TTcontext.fillRect(250,50,100,100);
TTcontext.stroke();
TTcontext.beginPath();
TTcontext.moveTo(600, 0);
TTcontext.lineTo(0, 200);
TTcontext.lineWidth = 5;
TTcontext.strokeStyle = "black";
TTcontext.stroke();
}
function validate() {
var TTinput = document.getElementById("3letters").value;
if(TTinput.length < 3 || TTinput.length > 3) {
alert("Please enter 3 letters");
}
var TTtest = document.getElementById("test");
var TTlive = document.getElementById("live");
if(TTtest.checked == true) {
alert("Input is valid");
}
else if(TTlive.checked == true) {
return ajaxStuff();
}
}
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
var TTresponse = TTrequest.responseText;
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML.TTresponse;
}
}
}
</script>
</head>
<body>
<h1>Tanner, Taylor</h1>
<canvas id = "myCanvas" width = "600" height = "200"></canvas> <br>
<form>
Enter 3 letters: <input type="text" id="3letters"> <br>
<input type = "radio" id = "test" value = "test">Test
<input type = "radio" id = "live" value = "live">Live <br>
<input type = "button" id = "check" value = "Send" onclick="validate()">
</form>
<div id="myDiv">
</div>
</body>
</html>
这是我们服务器上我的页面的链接:
cs.sfasu.edu/cs351121/exam2.html
另外,我知道它说的是考试,但这实际上只是我们为下周的实际考试提供的复习。我只是想弄清楚这是如何工作的,但不知道我做错了什么。
最佳答案
我不确定问题出在哪里。代码正确
好的,现在我明白了问题。您正在范围之外调用请求变量。您在 ajaxStuff 函数内声明 request 变量,因此只能在该区域中访问它。这就是为什么它是未定义的。试试这个:
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML=TTrequest.responseText;
}
}
}
要得到结果,只需这样做
TTrequest.send();
var response=TTrequest.responseText;
关于javascript - 使用 AJAX 从服务器发送和接收信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26666215/