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 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值