通过Jquery AJAX传递PHP变量

时间:2011-04-18 08:09:16

标签: php jquery ajax variables

我正在尝试学习Jquery AJAX函数,但我正在努力研究如何将PHP变量传递到我的主文档中。

这就是我目前所拥有的:

<script>
  var refreshId = setInterval(function() {
    $.ajax({
      url: "test.php",
      dataType: "json", //the return type data is jsonn
      success: function(data){ // <--- (data) is in json format
        $('#testdiv').html(data.test1);
        $('#testdiv').append(html(data.test2));
        //parse the json data
      }
    });

}, 1000);
</script>

5 个答案:

答案 0 :(得分:5)

您应该使用jsonxml格式并对其进行解析,然后获取变量。

<script src="jquery.js"></script>
<script>
    $.ajax({
      url: "test.php",
      dataType: "json", //the return type data is jsonn
      success: function(data){ // <--- (data) is in json format
        alert(data.test1);
        //parse the json data
      }
    });
</script>

on test.php

<?php

$test = array();
$test['test1'] = '1';
$test['test2'] = '2';
$test['test3'] = '3';

echo json_encode($test);
//echo nothing after this //not even html

答案 1 :(得分:1)

另一种方法(使用ajax但隐藏字段)将是:

$.ajax({
    type: 'POST',
    url: "test.php",
    dataType: "json", //the return type data is jsonn
    success: function(data){ // <--- (data) is in json format
        $('#testdiv').html('<input type="hidden" value="' + data.test1 + '" />');
    }
    error: ajaxError,
    dataType: "html"
});

使用表单中的内容,您甚至可以在下一个Postback中使用您的值而不直接传递它。

答案 2 :(得分:1)

index.php

上的ajax选项中使用 dataType ='json'

并在 test.php 上使用json_encode

$ret_array= array ($test1, $test2 and $test3);
echo json_encode($ret_array);

再次 index.php

现在,如果您想在* J * S文件中使用它,则可以通过对象导航或使用getJSON方法

进行访问

如果您想直接在 php 中使用该数据,请使用json_decode

json_decode($ret_array,true);

参考

json_encode
getJSON
json_decode

答案 3 :(得分:-1)

除非我极其错误地将其简单化为:

<?php
  include 'test.php';
?>

在index.php中包含test.php文件

然后你可以调用它们就好像它们是index.php中设置的变量一样,然后我会执行以下操作将它们转换为jQuery:

$(“#test1”)等...

<强>更新

  

我遇到的问题是   test.php中的变量将会发生变化   经常,然后这些需要   在index.php上更新。我只设置它们   分别为1,2和3来测试它。 -   user683526 1分钟前

在这种情况下,将它们设置在一个函数中并返回值。

答案 4 :(得分:-1)

你没有将它们传递给index.php,但你可以将它们添加为你的ajax加载的内容:

$test1 = '1';
$test2 = '2';
$test3 = '3';

echo $test1 . "<br/>" . $test2 . "<br/>" . $test3 . "<br/>";
相关问题