在javascript中调用php的替代方案?

I want to call php in a java script

I have read that this is forbidden:

document.getElementById('id1').innerHTML="<?php include my.php?>";

if I can't do this How can I load a php page content to a div with id1 when clicking an li:

<ul>
 <li onclick="javascriptFunction()">
 <li>
 <li>
</ul>
<div id="id1"></div>

There are two ways of achieving the goal.

It isn't so much that what you are trying to do is forbidden as much as it is simply impossible.

Option 1

Use an ajax call to your PHP code. In the callback of the ajax call, fill in the innerHTML.

Option 2

Use a template.

<script type="text/html" id="template-id1">
  <?php include my.php?>
</script>


<li onclick="setDiv()">

<script>
  function setDiv() {
    document.getElementById('id1').innerHTML =
      document.getElementById("template-id1").innerHTML;
  }
</script>

You could use AJAX (http://en.wikipedia.org/wiki/Ajax).

With a usage of library like jQuery (http://api.jquery.com/jquery.ajax/) you will have code like this:

$.ajax('my.php')
    .done(function(response) {
         $('#id1').html(response);
    })

Of course it's doable without any libraries like jQuery, but just requires a bit more code.

I don't know why that'd be forbidden. It's called bootstrapping.

But if you must:

my.php

echo 'whatever';

And then in a <script> tag, use $.ajax to call my.php and fill the appropriate element with the response.

You need to use ajax, if you don't want to use library try this:

var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

request.onreadystatechange=function() {
    if (request.readyState == 4 && request.status == 200) {
        document.getElementById("id1").innerHTML=request.responseText;
    }
};

request.open("GET","my.php",true);
request.send();

Or you could hide the div, then when you click on the link then make it visible.

<div id='id1' style='display:none;'>
    your content
</div>

function javascriptFunction() {
    document.getElementById('id1').style.display = 'block';
}

ready function:

function javascriptFunction () {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            document.getElementById("id1").innerHTML = xhr.responseText;
        }
    }
    xhr.open('GET', 'my.php', true);
    xhr.send();
}