简体   繁体   English

使用PHP中的参数调用Javascript函数

[英]Call Javascript function with parameters inside PHP

I have a javascript function which has some parameters (an array). 我有一个javascript函数,它有一些参数(一个数组)。 I want to call it inside php. 我想在php里面调用它。 Following is my code 以下是我的代码

 <script type="text/javascript">

<?php 

$task_list=array();
        foreach($tasks as $row2){


            $task_list=$row2;
        }

         echo "display_diagram(".$task_list.");";

        ?>

function display_diagram(var1){

     .........................
     .........................

 }

When I call it without any parameter it is working (I could displayed the content in javascript function. But when I give the parameter( it is an array it dose not working. Could you give this a solution? 当我调用它时没有任何参数它正在工作(我可以在javascript函数中显示内容。但是当我给出参数时(它是一个数组它不起作用。你能给这个解决方案吗?

The usual practice here is to create a separate PHP file that outputs JSON data and fetch that data using an AJAX request. 这里通常的做法是创建一个单独的PHP文件,输出JSON数据并使用AJAX请求获取该数据。 Below is an example of including JSON data inline, but I wouldn't typically recommend doing it like this, especially if the data is quite large. 下面是一个包含JSON数据内联的示例,但我通常不建议这样做,特别是如果数据非常大。


Use json_encode() to convert a PHP variable into something that can be used in JavaScript. 使用json_encode()将PHP变量转换为可在JavaScript中使用的变量。 With an associative array, you'll get a JavaScript object like {"a":1,"b":2,"c":3,"d":4,"e":5} . 使用关联数组,您将获得一个JavaScript 对象,{"a":1,"b":2,"c":3,"d":4,"e":5} With a non-associatve array, you'll get a JavaScript array like [1,2,3,4,5] . 使用非关联数组,您将获得类似[1,2,3,4,5]的JavaScript 数组

<script>
<?php
    $tasks = array(
        145 => array(
            'name' => 'Sorting Task',
            'owner' => 'user1'
        ),
        2343 => array(
            'name' => 'Processing Task',
            'owner' => 'user2'
        ),
        7266 => array(
            'name' => 'Another Task',
            'owner' => 'user1'
        ),
        8373 => array(
            'name' => 'Lorem Ipsum Task',
            'owner' => 'user3'
        )
    );
    echo 'display_diagram(' . json_encode($tasks) . ')';
?>

function display_diagram(tasks) {
    $.each(tasks, function (id, task) {
        console.log('Task #' + id + ': name=' + task.name + ', owner=' + task.owner);
    });
}
</script>

The JavaScript above uses jQuery to process the object. 上面的JavaScript使用jQuery来处理对象。 It should output the following in the JavaScript console: 它应该在JavaScript控制台中输出以下内容:

Task #145: name=Sorting Task, owner=user1
Task #2343: name=Processing Task, owner=user2
Task #7266: name=Another Task, owner=user1
Task #8373: name=Lorem Ipsum Task, owner=user3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM