简体   繁体   中英

Using Javascript (<script> and onload) with Ajax Calls

I wrote a previous question...which was rather confusing...so I have made this as simple as possible for everyone to understand.

I am using the PHP Built-In Web Server to test my PHP code. I don't know if there is any downside to this but that is what I am using at the moment (Advice would be helpful in regards to this as I evidently don't know what I'm doing, but I don't think it pertains to the problem)

I am trying to run the below code and specifically leggo() . Any scripts in page2.php do not work and onloads definitely don't work (for obvious reasons). These scripts not working is strange, but when all the scripts are moved into header.php they begin to work... except onload's . Is there an alternative to using onload . I'm guessing there is a problem with using AJAX and onload in conjunction . ---EDIT--- Code has been simplified for better understanding and per suggestion.

Code

heading.php

<!DOCTYPE html>
<html>
    <head>
        <script>
            function loadPageBelow(fileName) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    document.getElementById("content").innerHTML = xhttp.responseText;
                };
                xhttp.open("GET", fileName, true);
                xhttp.send();
            }
        </script>
    </head>
    <body>
        <p><b>THIS IS THE HEADER</b></p>
        <a onclick="loadPageBelow('page2.php')">Click to goto page 2</a>
        <div id="content">
            <?php
                include("starter.html");
            ?>
        </div>
    </body>
</html>

starter.html

<p>Welcome to the homepage</p>

page2.php

<canvas id="canvas" width="200px" height="200px">HI</canvas>
<script type="text/javascript" src="script.js"></script>
<script>
    leggo();
</script>

script.js

function leggo()
{
    var ctx = document.getElementById('canvas').getContext('2d');
    ctx.fillRect(0,0,100,100);
}

To run Web Server as I am doing go to the folder with the programs and type php -S localhost:8000 into the terminal. Then go the browser and type http://localhost:8000/heading.php

---------------------------------------EDIT---------------------------------------

I made the AJAX call use jquery:

$(document).ready(function(){
            $("a").click(function() {
                $("#content").load("page2.php");
            });
        });

And now I get the error:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/ .

Which may be something else. Any help would be much appreciated

I'm not sure I understand why you want to include HTML pages with JavaScript. This is not very usual and there are probably other ways to do this. In any case if you insist on doing this you need to make sure, especially when doing this that you don't have a full document. So starter.html should look more like this:

        <p>Welcome to the homepage</p>

And page2.php should look more like this:

    <script>
        function leggo() {
            var ctx = document.getElementById('canvas').getContext('2d');
            ctx.fillRect(0,0,100,100);
        }
    </script>
    <canvas id="canvas" width="200px" height="200px">HI</canvas>
    <script>
        leggo();
    </script>

Then you should add a call to the leggo() at in xhttp.onreadystatechange of loadPageBelow like this:

<html>
    <head>
        <script>
            function loadPageBelow(fileName) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    document.getElementById("content").innerHTML = xhttp.responseText;
                };
                xhttp.open("GET", fileName, true);
                xhttp.send();
            }
        </script>
    </head>
    <body>
        <p><b>THIS IS THE HEADER</b></p>
        <a onclick="loadPageBelow('page2.php')">Click to goto page 2</a>
        <div id="content">
            <?php
                include("starter.html");
            ?>
        </div>
    </body>
</html>

Since you are just loading content in the innerHTML of a div where the body has already been loaded , you should remove the and tags from starter.hml and page2.php . Also your script should be placed under all of your html markup . After you have done this , to initialize your leggo() function just add a document ready check.

Example

<script>

function leggo() {
                var ctx = document.getElementById('canvas').getContext('2d');
                ctx.fillRect(0,0,100,100);
  }

if(document.readyState == "complete"){

leggo()


}
</script>

I'm going out on a limb and assume your HTML is not parsed and the leggo() function is searching for canvas with id of canvas. That element is not written yet as page is interpreting the response.

I'm not going to criticize your codes. I would suggest you to defer the script until the page loads in web browser. To do this, separate your leggo() function from HTML and into external JavaScript file then update the HTML <script> tag to include defer and src attributes.

If external script is not possible, I would suggest including jQuery onload function to detect whether contents have loaded.

If jQuery is not possible, then I would suggest following this thread to detect whether contents are loaded without using jQuery.

Suggested Alternative: heading.php

<!DOCTYPE html>
<html>
<head>
    <script>
        function loadPageBelow(fileName) {
            this.document.location = "http://localhost/heading.php?page="+fileName;
        }
    </script>
</head>
<body>
    <p><b>THIS IS THE HEADER</b></p>
    <a onclick="loadPageBelow('page2.php')">Click to goto page 2</a>
    <div id="content">
        <?php
            if(isset($_GET['page'])) {
                include($_GET['page']);
            } else {
                include("starter.html");
            }
        ?>
    </div>
</body>
</html>

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