2012-07-31 86 views
0

我想通过我的函数open_boosters()从数组中获取单个变量,然后将该变量发送到我的PHP脚本。什么是正确的方法来做到这一点?从img标记调用JavaScript函数

我现在所拥有的就是这种产生随机数的JavaScript函数,称为open_boosters()

><img src="site3.php?"action="document.getElementById("?").innerHTML=open_boosters();"/> 

在我的PHP中,我应该简单地使用$ _GET方法绑定变量吗?

+0

它看起来像你的HTML是无效的。你正在尝试去site3.php?action = someid,但是你有一个单独的动作属性。你可以发布一个你到目前为止的jsfiddle(当然不包括php)吗? – james31rock 2012-07-31 00:22:05

回答

1

将行为移出HTML并放入<script>标记或更好的外部脚本文件(尽管可以将事件附加到HTML元素)是最佳做法。在这种情况下,没有理由将图像元素绑定到与图像无关的代码(它看起来像试图填充其他元素)。

<script> 
// This code will not work with older IE versions; you may 
// wish to use a library like jQuery to handle all the complexities 
// of browser compatibility; or you can avoid all this by putting 
// the script tag after your elements 
window.addEventListener('DOMContentLoaded', function() { 
    var rand = open_boosters(); 
    document.getElementById("?").innerHTML=rand; 
    document.getElementById("randImg").src = "site3.php?randomNumber"+rand; 
}, false); 
</script> 
<img id="randImg" /> 

然后在你的PHP代码:

<?php 
$_GET['randomNumber']; // Do something with it (though safely--e.g., do not add directly to a SQL string, etc.) 
?>