传递onClick到函数的JavaScript变量未定义

时间:2014-12-18 01:43:49

标签: javascript php mysql

我正在尝试用PHP,JavaScript和MySQL编写一个简单的投票脚本。将变量从href onclick参数传递给javascript函数时,我得到了一个未定义的'错误,我相信指的是变量。

我的PHP看起来像这样:

echo "<td class=\"uparrow\"><a href=\"javascript:void(0);\" onclick=\"upVote.call(". $row['serial'] ."); return false;\">&#8689;</a></td>";

哪个生成这样的HTML:

<td class="uparrow"><a href="javascript:void(0);" onclick="upVote.call(16); return false;">&#8689;</a>

功能如下:

function upVote(str) {
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("report_status").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","up_vote.php?serial="+str,true);
xmlhttp.send();
}

当upVote(str)函数调用up_vote.php时,由于某种原因,该变量没有被传递给PHP。

upVote PHP看起来像这样,直接通过URL访问时功能正常:

<?php
// Create Connection
$dbconnect=mysqli_connect("127.0.0.1","user","pass","table");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
//  echo "Connection Sucessful<BR><BR>";
}

// escape variables for security
if (isset($_GET['serial']))
{
    $serial = mysqli_real_escape_string($dbconnect, $_GET['serial']);
}

// define SQL call and fetch the result
$sql = "SELECT vote FROM urls WHERE serial = $serial";
$result = mysqli_query($dbconnect,$sql);

if (!$result) {
  die('Select Error: ' . mysqli_error($dbconnect));
}
//echo $sql . "<BR>"; // for error checking the SQL call

    while($row = mysqli_fetch_array($result)) {
        $return = $row['vote']+1;
    }

echo $return;  //Send result back to javascript

//Update the vote count in the database
$sql = "UPDATE urls SET vote=$return WHERE serial = $serial";
$result = mysqli_query($dbconnect,$sql);

if (!$result) {
  die('Update Error: ' . mysqli_error($dbconnect));
}

mysqli_close($dbconnect);
?>

1 个答案:

答案 0 :(得分:0)

要么不使用电话,要么按照预期的方式使用电话。在这种情况下,我认为你不应该使用它。

呼叫方法不像&#34;呼叫&#34;从一些使用它来调用子程序等的旧语言。你没有使用&#34;电话&#34;要正常调用函数,只需使用括号即可。如果abc是函数abc(),则调用函数,abc(123)传递123作为第一个参数。

javascript中的

call用于调用一个具有(通常)不同对象的函数作为&#34; thisArg&#34;或this。您可以将其视为能够apply对象的某些外部函数。实际上,有一种伴随方法apply

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

<td class="uparrow"><a href="javascript:void(0);" onclick="upVote(16); return false;">&#8689;</a>