问题
This question may have been asked a million times in the past but I am yet to come across a solution. So I ask again, hoping a less aggressive answer like "Look somewhere else" or "Don't repeat questions". If the reader feels the urge to type any of or similar to the aforementioned sentences, I can only request the reader to refrain from doing so and ignore this post completely. Any help is greatly appreciated.
The problem
In my program, an AJAX script works to communicate with a PHP script. There are no syntax errors. The AJAX receives the responseText
well and alerts it out.
alert(request.responseText); //this works as desired
But fails to return it to another function.
return(request.responseText); //this actually returns undefined
The full code Client file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>test</title>
<script type="text/javascript" language="javascript" src="ajax.js"></script>
<script type="text/javascript" language="javascript">
function createXMLHttp()
{
var xmlHttp = null;
if(window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajax_phprequest(data, php_file)
{
var request = createXMLHttp();
request.open("POST", php_file, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
document.write(request.responseText);
return request.responseText; //changed from return(request.responseText;);
}
}
}
function foo()
{
alert(ajax_phprequest("user=defuser&pass=123456","auth.php"));
}
</script>
</head>
<input type="button" id="somebutton" value="Call foo()" onclick="foo();" />
<body>
</body>
</html>
The full code auth.php file
<?php
$user;
$pass;
if (isset($_POST['user'])) $user = $_POST['user'];
else
{
echo 'err_u_Username is not specified';
exit();
}
if (isset($_POST['pass'])) $pass = $_POST['pass'];
else
{
echo 'err_p_Password is not specified';
exit();
}
if ($user = 'defuser' && $pass = '123456') echo ('That\'s right!');
else echo ('That\'s not right!');
?>
This can easily be solved by including the code in the same file as the document. But I wish to call the function from a different file and then return it to the file that has foo()
or the document. Simply, I want the AJAX function to return the responseText without it giving an `undefined' every time. If this has anything to do with synchronization: I want to know of any workarounds against this problem.
回答1:
The gist of it has already been mentioned, but I would like to go into a bit more depth as to why this doesn't work.
You have the following code:
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
document.write(request.responseText);
return(request.responseText);
}
}
Basically, you are setting the onreadystatechange
event to the value of an anonymous function. In that anonymous function, you are returning a value, which won't be returned to the caller of ajax_phprequest()
, but to the caller of the anonymous function, which is the event system and which doesn't care much about what value is returned.
This happens this way because it all happens asynchronously. In other words, you call ajax_phprequest()
and all that happens at that moment happens behind the screens. The user can continue working like nothing has happened. However, in the background, the php file is requested and hopefully returned. When that happens, you get to use the contents, but the moment at which you called ajax_phprequest()
has long since passed.
A proper way would be to use a callback function instead. It could look something like this:
function ajax_phprequest(data, php_file, callback)
{
var request = createXMLHttp();
request.open("POST", php_file, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
document.write(request.responseText);
callback(request.responseText);
}
}
}
function foo()
{
ajax_phprequest("user=defuser&pass=123456","auth.php", function (text)
{
alert(text);
});
}
回答2:
That is because the call is ASYNCHRONOUS so you cannot return from stack the usual way, i.e. your alert(ajax_phprequest("user=defuser&pass=123456","auth.php"));
is evaluated before the ajax response is returned ... you need to use a callback:
function callback( text ){
// something
}
...
if (request.readyState == 4){
callback( request.responseText );
}
来源:https://stackoverflow.com/questions/10279184/returning-ajax-responsetext-from-a-seperate-file