从单独的文件返回AJAX responseText [英] Returning AJAX responseText from a seperate file

查看:111
本文介绍了从单独的文件返回AJAX responseText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题过去可能被问过一百万遍,但是我还没有找到解决方案.所以我再问一次,希望能少一些 激进的答案,例如在其他地方看"或不要重复" 问题".如果读者希望输入以下任何一种或类似的内容 上述句子,我只能要求读者避免 因此,请完全忽略此帖子.任何帮助都是极大的 赞赏.

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.

问题

在我的程序中,AJAX脚本可与PHP脚本进行通信.没有语法错误. AJAX接收到responseText,并发出警报.

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

完整代码 客户端文件

<!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>

完整代码 auth.php文件

<?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!');
?>

可以通过在与文档相同的文件中包含代码来轻松解决此问题.但是我希望从另一个文件中调用该函数,然后将其返回到具有foo()的文件或文档中.简而言之,我希望AJAX函数返回responseText而不每次都给出"undefined".如果这与同步有关:我想知道解决此问题的任何解决方法.

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.

推荐答案

已经提到了其要点,但是我想更深入地探讨为什么它不起作用.

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.

您具有以下代码:

request.onreadystatechange = function() 
{
    if (request.readyState == 4)
    {
        document.write(request.responseText);
        return(request.responseText);
    }
}

基本上,您将onreadystatechange事件设置为匿名函数的值.在该匿名函数中,您将返回一个值,该值将不会返回给ajax_phprequest()的调用方,而是返回给该匿名函数的调用方,该匿名函数是事件系统,它并不关心值是什么返回.

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.

之所以以这种方式发生,是因为它们都是异步发生的.换句话说,您调用ajax_phprequest(),那一刻发生的所有事情都在屏幕后面发生.用户可以继续工作,就像什么都没有发生一样.但是,在后台请求并希望返回php文件.发生这种情况时,您可以使用其中的内容,但是调用ajax_phprequest()的那一刻已经过去了很长时间.

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);
    });
}

这篇关于从单独的文件返回AJAX responseText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆