javascript - 无法让简单的 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) ;
?>
解决方案
这一行:
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 和阻止默认值都会给你带来误导性的统计信息,因为右键单击链接并在新选项卡/窗口中打开它不会被记录。或者如果有人复制链接地址,打开一个新窗口并粘贴它,也不会被记录。
从根本上说,这种方法不能可靠地工作。您登陆的页面需要发送您登陆的信息。
推荐阅读
- python - 谁能解释以下 TensorFlow 代码?该函数如何识别输入并将其作为 numpy 数组?
- javascript - 当我使用 javascript 创建动态 html 页面时,Jquery 脚本没有加载到头部
- botframework - Microsoft Bot Framework 无法从网络聊天 UI 获取机器人中传递的用户名
- node.js - 聚合和分组 mongodb 数据
- javascript - 使用 PHP 将注册表单数据存储到文本文件
- c# - 如何在另一台机器上配置与我的 C# 应用程序数据库的连接
- javascript - 通过调用javascript函数设置输入值
- java - 有没有办法将 Thymeleaf 2 与 Spring Boot 2 一起使用?
- json - kubectl - 以 json 格式格式化资源配额值
- reactjs - create-react-app 使用代理实时重新加载