[英]Passing PHP variables through Jquery AJAX
我正在尝试学习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>
您应该使用json
或xml
格式并解析它,并获取变量。
<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>
在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
另一种方法(使用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中使用您的值而不直接传递它。
在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);
除非我非常误以为它简单如下:
<?php
include 'test.php';
?>
在index.php中包含test.php文件
然后你可以调用它们就像它们是index.php中设置的变量一样,然后我会执行以下操作将它们转换为jQuery:
$(“#test1”)等......
更新
我遇到的问题是test.php中的变量会不断变化,然后需要在index.php上更新这些变量。 我只将它们设置为1,2和3来测试它。 - user683526 1分钟前
在这种情况下,将它们设置在一个函数中并返回值。
你没有将它们传递给index.php,但你可以将它们添加为你的ajax加载的内容:
$test1 = '1';
$test2 = '2';
$test3 = '3';
echo $test1 . "<br/>" . $test2 . "<br/>" . $test3 . "<br/>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.