Javascript:如何在下面的代码中没有括号的javascript函数中传递参数?

时间:2016-03-08 18:45:04

标签: javascript ajax javascript-events javascript-objects visual-web-developer

我想传递handleServerResponse()函数中的参数,该函数在process()函数中调用,如给定代码所示(没有parantheses),但是当我尝试这样做时,代码不起作用。如何我传递参数吗?

function process(id){

if(xmlObject.readyState==0 || xmlObject.readyState==4){

    xmlObject.open("GET","dataProc.php?id=" + id, true);
    xmlObject.onreadystatechange = handleServerResponse;
    xmlObject.send(null);
}else{
    setTimeout("process()",1000);
}

}

function handleServerResponse(){
if(xmlObject.readyState==4){
    if(xmlObject.status==200){

        xmlResponse = xmlObject.responseXML;
        xmlDocumentElement = xmlResponse.documentElement;
        message = xmlDocumentElement.firstChild.data;
        //document.getElementById(str).className="btn btn-success disabled";
        document.getElementById("result").style.display='block';
        document.getElementById("result").innerHTML = message;

    }else{
        alert("Something went wrong");
    }
}

}

上面给出的代码工作正常,但我想通过这种方式添加更多功能: -

function process(id,id_val){

if(xmlObject.readyState==0 || xmlObject.readyState==4){

    xmlObject.open("GET","dataProc.php?id=" + id, true);
    xmlObject.onreadystatechange = handleServerResponse(idval); 

  //pass id_val to handleServerResponse();

    xmlObject.send(null);
}else{
    setTimeout("process()",1000);
}

}

function handleServerResponse(new_id){
if(xmlObject.readyState==4){
    if(xmlObject.status==200){

        xmlResponse = xmlObject.responseXML;
        xmlDocumentElement = xmlResponse.documentElement;
        message = xmlDocumentElement.firstChild.data;

       str="greendiv";
       str.concat(new_id);

        document.getElementById(str).className="btn btn-success disabled";
        document.getElementById("result").style.display='block';
        document.getElementById("result").innerHTML = message;

    }else{
        alert("Something went wrong");
    }
}

}

1 个答案:

答案 0 :(得分:0)

将可选参数与setTimeout()

一起使用
var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
  

param1param2等是附加参数,这些参数会传递给func指定的函数。