将数据从 php 发送到 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4120119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:59:33  来源:igfitidea点击:

send data from php to javascript

javascriptphp

提问by user403295

I have a question regarding data transmission from php to javascript. I gather some data from database and I format them like this:

我有一个关于从 php 到 javascript 的数据传输的问题。我从数据库中收集了一些数据,并将它们格式化如下:

for($i=0;$i<(sizeof($lt_periods_query['period_id']));$i++){

    $period_id   = $lt_periods_query['period_id'][$i];
    $lt_id       = $lt_periods_query['lt_id'][$i];
    $period_name = $lt_periods_query['period_name'][$i];
    $fDate       = $lt_periods_query['fromDate'][$i];
    $tDate       = $lt_periods_query['toDate'][$i];
    $minStay     = $lt_periods_query['min_stay'][$i];
    $nightly_rate= $lt_periods_query['nightly_rate'][$i];

    if (strStartsWith($fDate, $currentYear)=='true'){
        $year = $currentYear;
    } else if(strStartsWith($fDate, $nextYear)=='true'){
        $year = $nextYear;
    }

    $temp_period_details   =  array();
    $temp_period_details['period_id'] = $period_id;
    $temp_period_details['lt_id'] = $lt_id;
    $temp_period_details['period_name'] = $period_name;
    $temp_period_details['fromDate'] = $fDate;
    $temp_period_details['toDate'] = $tDate;
    $temp_period_details['min_stay'] = $minStay;
    $temp_period_details['nightly_rate'] = $nightly_rate;

    $periods[$year][$period_name] = $temp_period_details;
}

And I am able to see them when I print as like this:

当我像这样打印时,我能够看到它们:

echo "RULE for 6 days <br>";
$days= '5';
$selPeriod = 'off_peak';
$selYear = '2011';
echo $periods[$selYear][$selPeriod]['period_id'];
echo "<br>";
echo $periods[$selYear][$selPeriod]['lt_id'];
echo "<br>";
echo $periods[$selYear][$selPeriod]['period_name'];

I know that php is working on the server side and javascript is working on the client side. I want to get the data from javascript side by sending some parameters like this (I know why this is not working but I do not know how I can achieve such data transfers):

我知道 php 在服务器端工作,而 javascript 在客户端工作。我想通过发送一些这样的参数来从 javascript 端获取数据(我知道为什么这不起作用,但我不知道如何实现这样的数据传输):

    <script type="text/javascript">

    $(function(){

        getData();

        function getData(){

            var days= '5';
            var selPeriod = 'off_peak';
            var selYear = '2011';


            //var xxx     = '<?php echo $periods[\''+selYear+'\'][\''+selPeriod+'\'][\'fromDate\'] ;?>';
            //var xxx = '<?php include($periods['2011']['off_peak'][''])?>;

        }

    });

Can anyone advice me a way to gather data from php to javascript by sending some parameters.

任何人都可以建议我通过发送一些参数来收集从 php 到 javascript 的数据的方法。

回答by Kelstar

To communicate data structures from PHP to Javascript, inject a JSON value like this:

要将数据结构从 PHP 传递到 Javascript,请注入一个 JSON 值,如下所示:

<?php
     $xdata = array(
          'foo'    => 'bar',
          'baz' => array('green','blue')
     );
?>
<script type="text/javascript">
    var xdata = <?php echo json_encode($xdata); ?>;

    alert(xdata['foo']);
    alert(xdata['baz'][0]);

    // Dot notation can be used if key/name is simple:
    alert(xdata.foo);
    alert(xdata.baz[0]);
</script>

This can be used to properly escape scalars, arrays, objects, etc.

这可用于正确转义标量、数组、对象等。

回答by Daimon

Simple AJAX approach.

简单的 AJAX 方法。

Put all your data into single array. Then use json_encode to encode your data to JSON format.

将所有数据放入单个数组中。然后使用 json_encode 将您的数据编码为 JSON 格式。

$data_array = array();

//assigning your data to single array here
$data_array['param1'] = 'value1';

echo json_encode($data_array);

Then in your JavaScript code use AJAX to call you script. For example use great jQuery library for this (http://api.jquery.com/jQuery.getJSON/).

然后在您的 JavaScript 代码中使用 AJAX 调用您的脚本。例如,为此使用很棒的 jQuery 库 (http://api.jquery.com/jQuery.getJSON/)。

<script type="text/javascript">    

$.getJSON('http://www.example.com/my_script.php', function(data) {
    alert(data.param1); //this should alert 'value1'
});

回答by GordonM

There's the AJAX method, and there's the echoing method. The former is more flexible, while the latter is a lot simpler and doesn't require you to cope with AJAX errors.

有 AJAX 方法,还有回显方法。前者更灵活,而后者更简单,不需要您处理 AJAX 错误。

For the former, there are plenty of examples around the place on how to use AJAX. The latter can be achieved quite simply:

对于前者,这里有很多关于如何使用 AJAX 的示例。后者可以很简单地实现:

<script type="text/javascript">
var phpVar = <?php echo ($phpVar); ?>;
</script>

Which approach is approporite depends on what data your javascript needs and what it needs it for. If you're needing to do a lot of server interaction, then working with AJAX is the avenue you should be investigating. However, if all you need is an initial value to initialize a javascript, then the latter approach is a lot easier to implement.

哪种方法合适取决于您的 javascript 需要什么数据以及它需要什么数据。如果您需要进行大量服务器交互,那么使用 AJAX 是您应该研究的途径。但是,如果您只需要一个初始化 javascript 的初始值,那么后一种方法更容易实现。