通过Jquery AJAX传递PHP变量

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

这就是我目前所拥有的:

 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);  

您应该使用jsonxml格式并解析它,并获取变量。

   

test.php

  

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

另一种方法(使用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(''); } error: ajaxError, dataType: "html" }); 

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

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

 $test1 = '1'; $test2 = '2'; $test3 = '3'; echo $test1 . "
" . $test2 . "
" . $test3 . "
";

除非我非常误以为它简单如下:

  

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

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

$(“#test1”)等……

更新

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

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