[英]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.
在我的演示标签中,我发现它们正在自动功能的javascript函数中传递名称。
This is a function in my demo project, 这是我的演示项目中的功能,
<script>
$(function()
{
var sampleTags = ['c++', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
..................
.................
So , i want pass values from my php controller to this function ,inorder to get the autocomplete value from my database table 所以,我想将值从我的php控制器传递给此函数,以便从数据库表中获取自动完成值
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
Now how can i pass that $data["query"]
values into the above javascript function? 现在如何将
$data["query"]
值传递给上述javascript函数? Please help 请帮忙
You could echo the variable onto the page using PHP's json_encode
. 您可以使用PHP的
json_encode
将变量回显到页面上。 This function will convert a PHP array or object into a JSON object, which JavaScript can work with: 此函数会将PHP数组或对象转换为JSON对象,JavaScript可以使用该对象:
<script>
$(function() {
var sampleTags = <?php echo json_encode($query); ?>;
})();
</script>
But a better way would be to request these values via Ajax. 但是更好的方法是通过Ajax请求这些值。 Say you have a PHP script named
values.php
: 假设您有一个名为
values.php
的PHP脚本:
<?php
#...
#assign $query here
#...
echo json_encode($query);
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: 然后,在JavaScript(要使用
sampleTags
变量的页面上)中,可以使用jQuery的.ajax
函数发出简单的Ajax请求:
<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.
显然,您需要对其进行调整以适合您的环境。
You will have to write an ajax function for this 您将为此编写一个ajax函数
$.ajax(
url : "<?php echo site_url('controller/method')?>",
type : 'POST',
data : 'para=1',
success : function(data)
{
if(data){
var sampleTags = data;
}
}
);
Just echo your php variable 只需回显您的php变量
$(function()
{
var sampleTags = '<?php echo $data["query"]; ?>'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.