简体   繁体   中英

How to send multiple data from PHP to JavaScript

I don't know how to make a script for sending multiple variables from external php to javascript (jQuery) For exemple:

<?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
?>

and 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>

you can just output your data in JSON format and then load the data to JavaScript using ajax like so:

<?

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

echo json_encode($arrayWithData);

then call load the data using ajax:

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

Use a data structure, eg:

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

Then in your JS

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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