使用ajaxRequest.open将变量发送到php

时间:2013-03-18 22:31:27

标签: php javascript ajax

我有一个脚本,它使用ajaxRequest.open来调用php脚本。我想知道如何将变量发送到php文件。更具体地说,我有一个表单文本字段,我希望能够发送到php文件。

ajaxRequest工作正常,我只需要知道我如何发送变量以及php如何读取它。

这是调用我的php文件的(非常简略的)脚本...

}
  ajaxRequest.open("GET", "../../ajaxphp.php", true);
  ajaxRequest.send(null); 
}

3 个答案:

答案 0 :(得分:1)

将其作为查询字符串附加到请求中:

ajaxRequest.open("GET", "../../ajaxphp.php?myvar=thevalue", true);

然后在你的PHP中

$myvar = $_GET['myvar'];

答案 1 :(得分:1)

首先,您需要获取要发送给* .php的变量女巫的值 你可以通过这种方式来做到这一点:

var value = document.getElementById("someID").value;

或jQuery方式:

var value = $("#someID").val();

然后,您需要将变量放入ajax请求:

ajaxRequest.open("GET", "../../ajaxphp.php?variable="+value, true);
//The last argument in this line (witch is set a "true") want to say, that is a  asynchronous request 
ajaxRequest.send(null);
//null want to say, that you not sending any parameter, really is automatically sent in the first line of code

然后,当您在代码*中获取变量的值时。 php,可以做下一个:

<?php
$myVariable = $_GET["variable"];
echo $myVariable;
?>

或者像这样:

<?
$myVariable = $_REQUEST["variable"];
echo $$myVariable;
?>

答案 2 :(得分:0)

您只需将参数附加到网址即

即可发送数据
ajaxRequest.open("GET", "../../ajaxphp.php?foo=bar", true);

要使用javascript从输入字段获取值,您可以执行以下操作

var foo = document.getElementById('foo').value;

使用PHP

从URL获取值
$foo = $_GET['foo'];

完整示例

<input id="foo" name="foo" value="bar">

<script>

    var foo = document.getElementById('foo').value;
    ajaxRequest.open("GET", "../../ajaxphp.php?foo="+foo, true);
    ajaxRequest.send(null);

</script>

PHP文件

<?php

    $foo = $_GET['foo'];
    echo $foo;

?>