php:如何将数据库值传递到javascript / jquery函数 [英] php : how to pass database value into a javascript/jquery function
问题描述
我在我的项目中实施标签功能。
I am implementing tags feature in my project. In my demo tags i found they are passing names in a javascript function for the autocomple.
这是我的演示项目中的一个函数,
This is a function in my demo project,
<script>
$(function()
{
var sampleTags = ['c++', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
..................
.................
所以,我想从我的php控制器传递值到这个函数,从我的数据库表中获取自动完成值
So , i want pass values from my php controller to this function ,inorder to get the autocomplete value from my database table
For example i am getting tags values from my db in my Controller like this:
` $data["query"] = $this->ordermodel->fetch_orderlist();`
$this->load->view('tagpage', $data); //loading my page tag page where above function exists
code> $ data [query] 值到上面的javascript函数中?
请帮助
Now how can i pass that $data["query"]
values into the above javascript function?
Please help
推荐答案
您可以使用PHP的 json_encode
将变量回传到页面上,这个函数会将PHP数组或对象转换为JSON对象与:
You could echo the variable onto the page using PHP's json_encode
. This function will convert a PHP array or object into a JSON object, which JavaScript can work with:
<script>
$(function() {
var sampleTags = <?php echo json_encode($query); ?>;
})();
</script>
但更好的方法是通过Ajax请求这些值。假设您有一个名为 values.php
的PHP脚本:
But a better way would be to request these values via Ajax. Say you have a PHP script named values.php
:
<?php
#...
#assign $query here
#...
echo json_encode($query);
然后,在JavaScript(在您要使用 sampleTags
变量),您可以使用jQuery的 .ajax
函数来创建一个简单的Ajax请求:
Then, in JavaScript (on the page where you want to use the sampleTags
variable), you can use jQuery's .ajax
function to make an easy Ajax request:
<script>
var sampleTags;
$.ajax({
url: 'values.php'
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
</script>
我没有测试过这个例子。显然你会想调整它以适应你的环境。
I haven't tested this example. Obviously you'll want to tweak it to fit your environment.
这篇关于php:如何将数据库值传递到javascript / jquery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!