2011-04-27 280 views
0

我想将刚刚点击的标记的id值传递给正在使用greybox加载到页面上的php文件。将js变量传递给php变量

我得到了存储在一个名为linkID的js变量中的id,我可以通过location.href传递正确的id,但是这需要一个页面重新加载并且不能和greybox一起工作。可以,也许我该如何使用Ajax来帮助在后台发送这些信息? 任何帮助将不胜感激?

的JavaScript来获取点击的标签

<script type="text/javascript"> 
function myCallback(caller) 
{ 
    var linkID =caller.id; 
    location.href="species/butterfly.php?linkID=" + linkID; 
    alert(linkID); 
    } 
</script> 

在HTML中的index.php标签的ID

<div id="stump"> 
<a href="#" id="2" class="hedgehog descript" title="Hedgehog" 
rel="gb_page_center[1020, 550]" onclick="myCallback(this)"></a> 
</div><!--close stump div --> 

正试图收到该ID的butterfly.php页

<?php 
// Retrieve the URL variables (using PHP). 
$linkid = $_GET['linkID']; 
echo "Number: ".$linkid; 
?> 
+0

这是一个非常经典的AJAX的使用情况。你在使用像jQuery或Prototype这样的JavaScript库吗? ajax调用的语法会因库的不同或者您是否在使用而有所不同。 – 2011-04-27 20:36:46

+0

我正在使用jquery和原型为不同的事情,我确保他们werent冲突。灰箱使用prototype.js,所以这将是这个Ajax调用。感谢您的快速回复 – 2011-04-27 20:47:41

回答

0
var myCallback = function(caller){ 
    var linkID = caller.id; 

    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.open("POST","species/butterfly.php",true); 
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
    xmlhttp.send("linkID="+linkID;); 

    xmlhttp.onreadystatechange = function(){ 
     if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ 
      alert("Request complete. Data: "+xmlhttp.responseText); 
     } 
    }; 

    alert(linkID); 
} 

编辑:

纯GreyBox:

var myCallback = function(caller){ 
    var linkID = caller.id; 
    caller.href = "species/butterfly.php?linkID="+linkID; 
} 
+0

我试过这个,我认为它可能会工作,但是你会怎样编写标签的 2011-04-27 20:48:51

+0

不,我真的不知道什么是错误的,如果我离开href =“#”,因为它只是在greybox弹出区域加载主页。但是,如果我把href =“species/butterfly.php”放在蝴蝶页面中,但由于id没有显示,所以ajax请求似乎没有被发送或接收。如果您有任何其他建议,这将非常有帮助。谢谢 – 2011-04-27 21:23:51

0

这将转换JS变量PHP变量

<script> 
function sud(){ 

javavar=document.getElementById("text").value; 

document.getElementById("rslt").innerHTML="<?php 
$phpvar='"+javavar+"'; 
echo $phpvar.$phpvar;?>"; 
} 

function sud2(){ 
document.getElementById("rslt2").innerHTML="<?php 
echo $phpvar;?>"; 
} 

</script> 
<body> 
<div id="rslt"> 
</div> 

<div id="rslt2"> 
</div> 
<input type="text" id="text" /> 
<button onClick="sud()" >Convert</button> 
<button onClick="sud2()">Once Again</button> 

</body>