简体   繁体   English

如何将PHP数据传递到外部JavaScript

[英]How to pass PHP data to external JavaScript

I want to pass a variable, or rather a message, from my PHP file to my external JavaScript file. 我想将变量或消息从PHP文件传递到外部JavaScript文件。 I have looked at other answered questions and it seems like the PHP file is not really full PHP, it has some js codes in it. 我看了其他回答的问题,似乎PHP文件不是真正的完整PHP,它包含一些js代码。

I just want to pass a simple message so I can use alert() in the external js to show the message. 我只想传递一条简单的消息,以便可以在外部js中使用alert()来显示消息。

Should I use JSON(which I do not know how)? 我应该使用JSON(我不知道如何)吗? Or is there a simpler way? 还是有更简单的方法? I am new to all these so perhaps a simple explanation with an answer without jQuery would be appreciated. 我对所有这些都是新手,所以不带jQuery的简单答案可能会受到赞赏。

In the PHP file: 在PHP文件中:

function checkDuplicateTesterName($tester_name)
{
    $table_info = "TBL_TESTER_LIST";
    $query_string = "select tester_name from $table_info where tester_name = $tester_name";
    $result = @mysql_query($query_string) or die (mysql_error());
    $checkTester = mysql_num_rows($result);
    if($checkTester>0)
    {
        echo $message = "Error, please check again."; //I want to pass this
    }
}

In the external js file: 在外部js文件中:

function checkTester()
{
    var tester_name = document.getElementById("tester_name").value;
    var page = "database.php";

    var parameters = "&tester_name="+tester_name+"&action=check";
    var xmlhttp = new XMLHttpRequest();

    if(xmlhttp==null)
    {
        alert("Your browser does not support ajax!");
        return false;
    }
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4)
        {
            alert("function success."+message); //Alert error message from PHP here
        }
    };
    xmlhttp.open("GET", page+"?"+parameters, true);
    xmlhttp.send(null);
}

The response is in the responseText field of the XHR object, so you need to do: 响应位于XHR对象的responseText字段中,因此您需要执行以下操作:

xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4)
    {
        var message = xmlhttp.responseText;
        alert("function success."+message); //Alert error message from PHP here
    }
};

You don't need to use JSON if you're just returning a string. 如果您只是返回一个字符串,则无需使用JSON。 JSON is useful if you're returning an array or object. 如果您要返回数组或对象,则JSON非常有用。

You can do it by defining global variable which value comes from php like this one below. 您可以通过定义全局变量来实现,该变量的值来自php,如下所示。

<script type="text/javascript">
   var message = '<?= $message ?>';
</script>

That is the simple way. 那是简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM