首页 > 解决方案 > 无法让简单的 Javascript 在 Firefox 中工作

问题描述

我对 PHP、MySQL、HTML 和 CSS 有相当的经验,但我在学习 Javascript 的早期阶段很挣扎。我有一个在 IE、Opera 和 Chrome 中按预期运行的脚本,但在 Firefox 中没有。

这是两个相关的脚本。这是我在这里的第一篇文章,所以如果我做得不对,我深表歉意。尽管如此,我们将不胜感激。

<html>
<!-- The purpose of this script is to to capture the details of the hotlink that was clicked without affecting the visible hotlink destination -->
<!-- This script works in IE, Chrome and Opera, but not Firefox -->

<head>
<title>Dev</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script src="jQuery.js"></script>

<script>
function myBasic(pgnm){
        var page = pgnm ;
        var theLink = encodeURIComponent(document.getElementsByClassName('theLink')) ;
        // the alert window displays the correct data
        window.alert(theLink + "\n" + page);
        jQuery.post("catchIt.php?link=" + theLink + "&pg=" + page) ;
        return true ;
    }   
</script> 

</head>

<body bgcolor="#FFFFFF" text="#000000">

<!-- This is a series of many hotlinked URLs that need to be recorded and stored in a mySql table -->
<!-- The pagename and hotlinks will be inserted via a PHP script -->

  <p><a onClick="myBasic('pagename.php');" href="destination.php" class="theLink">(Not) Working script</a></p>
  <p><a onClick="myBasic('anotherPagename.php');" href="http://example.com/destination.php?a=1&b=2" class="theLink">Another (Not) Working script</a></p>

</body>
</html>

(catchIt.php)

$thisString  = $_GET['link'] ;
$page = $_GET['pg'] ;

$thisDate = date('Y-m-d H:i:s') ;
$thisIp = $_SERVER['REMOTE_ADDR'] ;

// the remained of this code has already been developed to write the details to the mySql table
// the code below is there to prove the success of this script
$thisString .= '
' . $thisDate . '
' . $thisIp . ' 
' . $page ;

$file = fopen("theWords.txt","w");

fwrite($file, $thisString) ;

fclose($file) ;

 ?>

标签: javascript

解决方案


这一行:

var theLink = encodeURIComponent(document.getElementsByClassName('theLink')) ;

在 Chrome 上设置theLink为。"%5Bobject%20HTMLCollection%5D"如果目标是获取href被点击的链接,您需要将链接传递到您的函数中,并使用其href属性。最小的改变来做到这一点:

<a onClick="myBasic(this, 'pagename.php');" ...

function myBasic(element, pgnm){
    var page = pgnm ;
    var theLink = encodeURIComponent(element.href);
    // ...

但是,然后,您必须发送一个同步ajax 请求(这是一个非常糟糕的主意),以确保在页面因跟随链接而被拆除之前完成发布。

您可以阻止默认操作(按照链接),然后在 ajax 完成时导航到页面。

但是同步 ajax 和阻止默认值都会给你带来误导性的统计信息,因为右键单击链接并在新选项卡/窗口中打开它不会被记录。或者如果有人复制链接地址,打开一个新窗口并粘贴它,也不会被记录。

从根本上说,这种方法不能可靠地工作。您登陆的页面需要发送您登陆的信息。


推荐阅读