如何将 javascript 值发送到 PHP 页面,然后在 PHP 页面中引用该值?
假设我有某种 javascript AJAX 解决方案,例如:
var id=5;
obj.onreadystatechange=showContent;
obj.open("GET","test.php",true);
obj.send(id);
我想在 test.php 中使用这个特定的 id。我怎样才能做到这一点?
将您的代码更改为:
obj.open("GET","test.php?id=" + id,true);
obj.send();
然后在 test.php 中使用$_GET['id']
在 javascript 中(我正在制作一个函数,以便您可以将其分配给其他事件)
//jQuery has to be included, and so if it's not,
//I'm going to load it for you from the CDN,
//but you should load this by default in your page using a script tag, like this:
//<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
window.jQuery || document.write('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"><\/script>')
function sendValueGet(passedValue){
jQuery.get('test.php', { value: passedValue });
}
function sendValuePost(passedValue){
jQuery.post('test.php', { value: passedValue });
}
然后在你的 PHP 中:
<?php
if( $_REQUEST["value"] )
{
$value = $_REQUEST['value'];
echo "Received ". $value;
}
?>
请注意,我在 javascript“object”{ value: ... }
和 PHP“REQUEST”变量中使用了“value”$_REQUEST["value"]
如果你想给它一个不同的参考名称,那么你需要在两个地方都改变它。
使用 GET 或 POST 是您的偏好。
//得到
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
xmlhttp.open("GET","test.php?q="+id,true);
xmlhttp.send();
在 test.php 中
$id=$_GET['q']
//邮政
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
xmlhttp.open("POST","test.php",true);
xmlhttp.send("x=id");
在 test.php 中
$id=$_POST['x']