使用jQuery Ajax load()[duplicate]从PHP文件加载变量

This question already has an answer here:

Assuming my example.php looks like this:

<?php 
$variable = "I am a variable";
?>

and on another page I have:

<div id="loadme"></div>

How can I get that variable to my div?

Can it be achieved by using .load()?

I can imagine could be something like this:

$('#loadme').load("example.php", $variable);

Am I even close?

</div>

You're close, you need to echo the variable in the PHP file -

<?php
$variable = "foo";
echo $variable;
?>

Then load like this -

$('#loadme').load('example.php');

The content of #loadme will now be 'foo'.

EDIT: Based on the OP's comments -

Each echo containing a variable could be a div with an id, e.g.,

echo '<div id="foo">$variable</div>';

Then your load statement would look like this -

$('#loadme').load('example.php #foo');

Now #loadme would contain the variable echoed in that div. This is not an efficient plan if the variables are to be re-used by JavaScript/jQuery code.

Yes you are close I think. Just a simple change

<?php 
    $variable = "I am a variable";
    echo $variable;
    ?>

You can request your example page with AJAX like that:

<?php
// exemple.php

json_encode(array(
  'my_var' => 'my_value'
));

?>

<!-- something.html -->
<script>
  $(document).ready(function() {
    $.ajax({
      url: 'exemple.php',
      dataType: 'json'
    }).done(function(data)) {
      alert(data.my_var);
    }
  })
</script>