douhui8454 2015-05-26 00:44
浏览 62
已采纳

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

I want to pass a variable, or rather a message, from my PHP file to my external JavaScript file. 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.

I just want to pass a simple message so I can use alert() in the external js to show the message.

Should I use JSON(which I do not know how)? 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.

In the PHP file:

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:

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);
}
  • 写回答

2条回答 默认 最新

  • duanji4870 2015-05-26 01:05
    关注

    The response is in the responseText field of the XHR object, so you need to do:

    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 is useful if you're returning an array or object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答