I have an AJAX post function I am using for my communication between my server & the users webpage. But I have a problem with dealing with the response from the server in my resuable function.
If you see the following example you will see that the function outputEmailDetailsResult() is called & run on the line "post( "forgotPass.py",开发者_运维百科 emailParam, outputEmailDetailsResult() );", ie, when the function is passed as a param. But it should only run inside the post function in reation to the server response:
var xmlhttp;
function post( dest, params, callbackFunction )
{
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)
{
callbackFunction;
}
}
xmlhttp.open("POST",dest,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send( params ); // "fname=Henry&lname=Ford");
}
function emailLoginDetails()
{
var emailParam = "email=sam"; // + document.getElementById( "forgotEmail" ).innerText;
alert( emailParam );
post( "forgotPass.py", emailParam, outputEmailDetailsResult() );
}
function outputEmailDetailsResult()
{
try
{
document.getElementById( "statusOutput" ).value = xmlhttp.responseText;
}
catch ( ex )
{
document.getElementById( "statusOutput" ).value = "Failed to get response from server";
}
}
I am new to passing functions as a parameters(I think they're called callbacks?) & I am unsure I am doing it correctly?
I guess what you need to do is to remove parentheses from the callback parameter;
In your emailLoginDetails() function:
post( "forgotPass.py", emailParam, outputEmailDetailsResult );
Move the parentheses from the callback parameter to the function. Like this.
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callbackFunction();
}
...
post( "forgotPass.py", emailParam, outputEmailDetailsResult);
What you did was calling outputEmailDetailsResult() before post, so you were actually passing the result of the outputEmailDetailsResult() function as the parameter rather than the function itself as the parameter.
加载中,请稍侯......
精彩评论