我需要帮助完成我需要做的任务。基本上问题是数字猜谜游戏。根据我们的学号,我们在区间[0,1023]中分配了一个号码,我们有11个猜测来获得正确的号码。我知道我必须使用二进制搜索来获取数字,我唯一的问题是连接到服务器并获得结果。
我们得到了这个:
示例请求如下所示:
http://142.132.145.50/A3Server/NumberGuess?snum=1234567&callback=processResult&guess=800
并且还要求请求返回以下参数: 1:用于确定您的猜测是否相等,小于或大于该数字的代码 2:消息字符串 3:我的申请所做的猜测数量
这是我到目前为止所尝试的,就像测试服务器请求一样。我得到的只是“对象HTMLHeadingElement”
window.onload = function() {
newGuess();
}
function newGuess() {
var url = "http://142.132.145.50/A3Server/NumberGuess?snum=3057267&callback=processResult&guess=600";
var newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement = document.getElementById("jsonp");
var head=document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
function processResult(code,message,guesses) {
var code = document.getElementById("code");
var message = document.getElementById("message");
var guesses = document.getElementById("guesses");
code.innerHTML = code;
message.innerHTML = message;
guesses.innerHTML = guesses;
}
编辑:我的代码的当前状态。
window.onload = function() {
min = 0;
max = 1023;
mid = 0;
setInterval(newGuess,1000);
};
function newGuess() {
mid = Math.floor((max-min)/2);
var url = "http://142.132.145.50/A3Server/NumberGuess?snum=3057267&callback=processResult&guess="+mid;
var newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement = document.getElementById("jsonp");
var head=document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
function processResult(codeJ,messageJ,guessesJ) {
code = document.getElementById("code");
message = document.getElementById("message");
guesses = document.getElementById("guesses");
code.innerHTML = codeJ;
message.innerHTML = messageJ;
guesses.innerHTML = guessesJ;
if(codeJ == 0){
return;
}else if(codeJ == -1){
min = mid + 1;
}else if(codeJ == 1){
max = mid -1;
}
console.log(mid);
}
答案 0 :(得分:1)
检查您的变量名称。你正在覆盖功能代码。
像
这样的东西code.innerHTML = code;
message.innerHTML = message;
guesses.innerHTML = guesses;
只是CAN' T,你应该自己看问题......