最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript XMLHttpRequest open php file and execute more javascript - Stack Overflow

programmeradmin1浏览0评论

I have a main page, call it Main.php. On this page, is a button that when clicked, sets a div's innerHTML (already on Main.php, called divResults) with the results from Results.php.

When Results.php is called, the returned HTML "These Are The Results" is properly received and set as the contents to divResults on Main.php. However, any javascript from Results.php is not executed. As an example, I attempt to do a simple window.alert. Here is example code:

Main.php link button to begin the action:

<img src="$MyImageSource" onclick=\"ExpandDropdownDiv()\" />

Main.php javascript function ExpandDropdownDiv():

function ExpandDropdownDiv(){

    if (window.XMLHttpRequest)/* code for IE7+, Firefox, Chrome, Opera, Safari */
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {/* code for IE6, IE5 */
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
        {
            document.getElementById("divResults").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","Results.php",true);
    xmlhttp.send();

}

Results.php code example:

<script type="text/javascript">
    alert("Success");
</script>
These Are The Results

------------------ Edit - Update ------------------

The simple alert, from Results.php is just an example. If I were able to get this to work, I believe I could solve the rest of my problem on my own. However, I noticed a few ments suggesting to just place the alert in Main.php's javascript after i set the div's innerHTML. So, let me explain what I truly want to do with the javascript, after the div is set.

Image 1, shows some normal "Select" html elements, that have been transformed using jquery and the dropdown-check-list extension (.js). When the user clicks the colorful down arrow at the bottom, the div expands, (image 2) and two more "Select" elements are generated within this other .php file... the html is returned, and placed in the div. Thus, i do not need to reload the entire page, and can place the new select dropdowns just beneath the existing ones.

The problem is, to "transform" these normal select elements, there is some javascript that needs to be executed against that HTML:

$(document).ready(function() {
     $(".MultiSelect").dropdownchecklist(  {firstItemChecksAll: true, maxDropHeight: 300 , searchTextbox: true, width: 100, textFormatFunction: function(options) {
        var selectedOptions = options.filter(":selected");
        var countOfSelected = selectedOptions.size();
        var size = options.size();
        switch(countOfSelected) {
        case 0: return "All";
        case 1: return selectedOptions.text();
/*      case size: return "All"; */
        default: return countOfSelected + " selected";
        }
    } 
    }
    ); 
}

So, somehow I need to be able to execute javascript against the HTML that is generated from this other .php file. And simply calling the above code, after my divs innerHTML is filled, only re-generates the already existing dropdowns, not the two new ones.

Example Images

I have a main page, call it Main.php. On this page, is a button that when clicked, sets a div's innerHTML (already on Main.php, called divResults) with the results from Results.php.

When Results.php is called, the returned HTML "These Are The Results" is properly received and set as the contents to divResults on Main.php. However, any javascript from Results.php is not executed. As an example, I attempt to do a simple window.alert. Here is example code:

Main.php link button to begin the action:

<img src="$MyImageSource" onclick=\"ExpandDropdownDiv()\" />

Main.php javascript function ExpandDropdownDiv():

function ExpandDropdownDiv(){

    if (window.XMLHttpRequest)/* code for IE7+, Firefox, Chrome, Opera, Safari */
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {/* code for IE6, IE5 */
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
        {
            document.getElementById("divResults").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","Results.php",true);
    xmlhttp.send();

}

Results.php code example:

<script type="text/javascript">
    alert("Success");
</script>
These Are The Results

------------------ Edit - Update ------------------

The simple alert, from Results.php is just an example. If I were able to get this to work, I believe I could solve the rest of my problem on my own. However, I noticed a few ments suggesting to just place the alert in Main.php's javascript after i set the div's innerHTML. So, let me explain what I truly want to do with the javascript, after the div is set.

Image 1, shows some normal "Select" html elements, that have been transformed using jquery and the dropdown-check-list extension (.js). When the user clicks the colorful down arrow at the bottom, the div expands, (image 2) and two more "Select" elements are generated within this other .php file... the html is returned, and placed in the div. Thus, i do not need to reload the entire page, and can place the new select dropdowns just beneath the existing ones.

The problem is, to "transform" these normal select elements, there is some javascript that needs to be executed against that HTML:

$(document).ready(function() {
     $(".MultiSelect").dropdownchecklist(  {firstItemChecksAll: true, maxDropHeight: 300 , searchTextbox: true, width: 100, textFormatFunction: function(options) {
        var selectedOptions = options.filter(":selected");
        var countOfSelected = selectedOptions.size();
        var size = options.size();
        switch(countOfSelected) {
        case 0: return "All";
        case 1: return selectedOptions.text();
/*      case size: return "All"; */
        default: return countOfSelected + " selected";
        }
    } 
    }
    ); 
}

So, somehow I need to be able to execute javascript against the HTML that is generated from this other .php file. And simply calling the above code, after my divs innerHTML is filled, only re-generates the already existing dropdowns, not the two new ones.

Example Images

Share Improve this question edited Feb 11, 2011 at 17:09 Adam asked Feb 11, 2011 at 16:04 AdamAdam 2253 gold badges7 silver badges14 bronze badges 7
  • why not just put the alert("Success'); inside ajax callback? – KJYe.Name Commented Feb 11, 2011 at 16:09
  • @kjy112 - can you give me an example i will try? i barely got this code to work and dont even fully understand it. – Adam Commented Feb 11, 2011 at 16:13
  • The easiest way to go about it Adam is to not embed the javascript within your PHP, but instead perform the JavaScript after you inject the php result in the ajax callback function. – KJYe.Name Commented Feb 11, 2011 at 16:51
  • @Adam if u just want to get it up and running just look at the Easy Part under my answer – KJYe.Name Commented Feb 11, 2011 at 16:56
  • @kjy - your answer was VERY easy to read and understand, for that i thank you very much! i tried your example though, and still got the error that result was undfined... =[ – Adam Commented Feb 11, 2011 at 17:12
 |  Show 2 more ments

3 Answers 3

Reset to default 6

Here is a good read on understanding what you are doing: Eval embed JavaScript Ajax: YUI style

Making your code work with using eval(); but its not remend for various reasons:

Let's take your php and modify it like this:

<script type="text/javascript">
    function result() {
        alert("Success");
    }
</script>
These Are The Results

and This is the callback function from AJAX. result(); is not executed because it doesn't get evaluated, and thus does not exist. which is in your case

if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
        {
            document.getElementById("divResults").innerHTML=xmlhttp.responseText;
            result(); // this function is embedded in the responseText
                      // and doesn't get evaluated. I.e. it doesn't exist
}

in order for the browser to recognize the result(); you must do an eval(); on all the JavaScript statements with in the script tags that you injected into the div with id divResults:

if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
        {
            document.getElementById("divResults").innerHTML=xmlhttp.responseText;
            var myDiv = document.getElementById("divResults");
            var myscripz = myDiv.getElementsByTagName('script');
            for(var i=myscripz.length; i--;){
                   eval(myscripz[i].innerHTML);
            }
            result(); //alerts success
}

Easy Way:

The easiest way i would do it is basically remove the JavaScript from the php and display the content, and after callback just do the rest of the JavaScript within the callback function php:

 echo 'These Are The Results';

JavaScript:

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
    {
        document.getElementById("divResults").innerHTML=xmlhttp.responseText;
        alert('success'); // or whatever else JavaScript you need to do
    }
}

try to wrap the javascript code from Result.php in a function and call it after inserting it like :

<script type="text/javascript">
    function result() {
        alert("Success");
    }
</script>
These Are The Results

and

   if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
    {
        document.getElementById("divResults").innerHTML=xmlhttp.responseText;
        if(result) result();
    }

Your results.php needs to be something like...

echo 'eval("function results() { alert(\'success\'); }");';

And then call the results function.

发布评论

评论列表(0)

  1. 暂无评论