使用单击按钮的ID运行AJAX请求

Run AJAX request using ID from button clicked

本文关键字:运行 AJAX 请求 ID 单击 按钮      更新时间:2023-09-26

为了对几个不同的文件使用相同的AJAX请求,我有一个AJAX请求,它使用按钮的ID来选择所需的下一个文件。

按钮看起来是这样的:

<button type="button" id="question_1" onclick="nextQuestion(this.id)">Start the challenge</button>

AJAX请求的开头有一个按钮ID作为参数:

function nextQuestion(buttonID)

当按钮被按下时,buttonID变量被收集:

var splitID = buttonID.split('_'); //split the ID from the end of the button
var questionID = splitID.pop();

然后使用这个ID生成请求的文件名。

xmlhttp.open("GET","question" + questionID + ".php",true); // concatenate button ID to filename

由于某种原因,即使我在另一个区域工作,这也不起作用。我想不出我做错了什么。完整的AJAX请求是:

function nextQuestion(buttonID){
quizScore = 0;
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("gameWrapper").innerHTML=xmlhttp.responseText;
    }
  }
var splitID = buttonID.split('_'); //split the ID from the end of the button
var questionID = splitID.pop();
xmlhttp.open("GET","question" + questionID + ".php",true); // concatenate button ID to filename
}

缺失xmlhttp.send(null);函数

试题:

function nextQuestion(buttonID){
    quizScore = 0;
    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");
    }
    var splitID = buttonID.split('_'); //split the ID from the end of the button
    var questionID = splitID.pop();
    xmlhttp.open("GET","question" + questionID + ".php",true); // concatenate button ID to filename
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("gameWrapper").innerHTML=xmlhttp.responseText;
        }
    };
    xmlhttp.send(null);//send request
}