【问题标题】:calling two js functions and don't print message调用两个js函数并且不打印消息
【发布时间】:2012-11-04 14:20:48
【问题描述】:

我在 ajax 中有问题,它没有打印出我想要的消息。让我们解释一下。 在 php 代码中,我有一个输入标签:

<input type="submit" id="login_button_add" name="submit" value="Add" 
onclick="add_building(); showbuildings( );" />

这两个js函数分别是:

function add_building(){
    var str1=document.getElementById("building_name").value;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("txtHint10").innerHTML=xmlhttp.responseText;}
    }
    xmlhttp.open("GET","add_building.php?q="+str1,true);
    xmlhttp.send();
}

add_building.php 我在数据库中添加一行并打印消息。查询工作正常,但它不会在我的页面中打印带有我在我的 html 代码中的 id 的消息。我认为问题在于我调用了第二个 js 函数。因为当我单独调用add_building() 时,它可以完美运行(打印消息)。

add_building.php的php代码为:

$q=$_GET["q"];


if ($q!==''){
$link= mysqli_connect(...);

mysqli_set_charset($link, "utf8");
$sql="SELECT * FROM buildings WHERE name='$q'";
$result = mysqli_query($link,$sql);

if (!mysqli_num_rows($result)){
mysqli_set_charset($link, "utf8");
$sql="INSERT INTO buildings VALUES ('','$q','')";
$result =mysqli_query($link,$sql);
echo "The building added successfully.";
}
else {echo 'Building name exists. Try a different.';}

@ db_close($link);
}
else{echo 'Please insert a name.';}

另外一个js函数是:

function showbuildings(str)
{
    if (str=="")
    {
        document.getElementById("show_buildings_js").innerHTML="";
        return;
    } 
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("show_buildings_js").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","showbds.php?q=",true);
    xmlhttp.send();
}

在这个函数中,我在我的页面中打印表格。效果很好。

问题是来自add_building.php 的消息不会在id='txtHint10' 中打印, 尽管add_building.php 中的所有其他人都在工作。我认为问题在于我调用了第二个 js 函数并且我有两个 xmlhttp.responseText。因为当我单独调用 js 函数 add_building() 时,它可以完美运行并打印消息。

【问题讨论】:

  • 你有一个 sql 注入问题,切换到带有绑定变量的预处理语句或在你的变量上使用mysqli_real_escape_string(推荐第一个......)。
  • 全局变量的攻击。学习使用var

标签: php javascript sql ajax dom


【解决方案1】:

问题是您正在用第二个 javascript 函数覆盖 xmlhttp 变量。结果是只执行了第二个函数的回调。

要让这两个函数彼此独立工作,您需要使用不同的变量名或在每个函数中使用 var xmlhttp; 本地声明它们(更简洁的解决方案)。

请注意,javascript 中变量的范围是全局的,除非您在函数中使用 var 声明它。

【讨论】:

  • 谢谢你的回答..你能给我一个例子,如何在 xmlhttp 上命名。
  • @user1827879 最简单的解决方案是使用var xmlhttpd; 启动每个函数。这样变量就被定义在函数的局部范围内。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多