如何向PHP页面发送javascript值,然后在PHP页面中引用该值?
如何向PHP页面发送javascript值,然后在PHP页面中引用该值 假设我有某种javascript AJAX解决方案,例如:如何向PHP页面发送javascript值,然后在PHP页面中引用该值?,php,ajax,Php,Ajax,如何向PHP页面发送javascript值,然后在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=" +
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中使用$\u GET['id']/p>//GET
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']
$id=$_POST['x']
//职位
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=$_GET['q']
$id=$_POST['x']
在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对象{value:…}和PHP请求变量$\u REQUEST[value]中使用value
如果您想给它一个不同的引用名称,那么您需要在两个地方都更改它
使用GET或POST是您的首选。javascript代码……我想使用idNever,ever命名变量obj。任何人看到这段代码都会立即问什么是obj?告诉你你的代码没有表达意图。@jcolebrand你能给我建议一个链接吗?是的,不是每个人出生时都会学习母语英语。如果请求方法是post,我不确定,但我假设它类似于obj.openPOST,test.php,true;var params={'id':id};obj.sendparams;但是get方法并不那么安全…?get方法的参数在URL中是可见的。他问如何在test.php中访问id,你没有解释尝试这个xmlhttp.openPOST,test.php,true;xmlhttp.setRequestHeaderContent类型,application/x-www-form-urlencoded;xmlhttp.sendx=id;