如何将多个数据从PHP发送到JavaScript

时间:2014-01-28 16:19:29

标签: javascript php jquery variables

我不知道如何制作一个脚本,用于将多个变量从外部php发送到javascript(jQuery) 例如:

<?php
  $test = "tets"; -->this, I want something this, no echo
  $dock = "dock"; --
  echo $test; -->no, I don't want echo in PHP script
  echo $dock; -->no, I don't want echo in PHP script
?>

和JS

<script>
function(){
  $.post("url", {Some_Thing: "Some_Thing"}, function (data) {
  alert(data); --> no, I don't want echo in PHP script
  alert($test); --> this, I want something this, no echo
  alert($dock);
  }
}
</script>

2 个答案:

答案 0 :(得分:0)

您只需输出JSON格式的数据,然后使用ajax将数据加载到JavaScript,如下所示:

<?

$arrayWithData = array('data1' => 123, 'data2' => 555);

echo json_encode($arrayWithData);

然后使用ajax调用加载数据:

$.ajax({
    'url' : 'php-data-script.php',
    'method' : 'get',
    'dataType' : 'json'
}).done(function(data) {
    // do whatever you want with the data
    console.log(data);
});

答案 1 :(得分:0)

使用数据结构,例如:

<?php
   $data = array('test', 'dock');
   echo json_encode($data);

然后在你的JS中

$.post('url', {...}, function (data) {
    alert(data[0]);
}, 'json');
  ^^^^^^^^--- tell jquery you're expecting back some json