开发者

Request for the simplest jquery-ajax tutorial

开发者 https://www.devze.com 2023-03-26 07:40 出处:网络
I am a bit new to ajax and trying to understand how it works with jQuery. I am searching fo开发者_如何学运维r an example for the simplest tutorial just to understand how to get started.

I am a bit new to ajax and trying to understand how it works with jQuery.

I am searching fo开发者_如何学运维r an example for the simplest tutorial just to understand how to get started.

Let's say - that when the page loads I want that to ask for server (PHP) to insert inside body tag the words "Hello world"

How do I do that? (in the html and in the server side file)


I suggest you take a look at the jQuery documentation. The documentation for load provides an example:

$('#result').load('ajax/test.html');

that loads the content of ajax/test.html and displays it in an element with id result

We can then mimic it and call the load function inside the ready function that is executed after the page has loaded. We use the selector body to select the body element(s) and instruct the content of the(se) element(s) to be replace with the content of ajax.php

$(document).ready(function() {
  $('body').load('ajax.php');
});


OK in your HTML:

<!DOCTYPE html>  
<html lang="en">  
<body>

    <div id="my_content">Nothing here yet</div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>    
    <script>

        // When jQuery is ready
        $(function(){

            // Get the contents of my_page.php
            $.get("/my_page.php", function(data){

                // When the contents of my_page.php has been 'got' 
                // load it into the div with the ID 'my_content'
                $("#my_content").html(data);

            });

        });

    </script>
</body>
</html>

Then in your my_page.php PHP file:

<?

    // This is what jQuery will get
    echo "Something is here now!";

?>


index.html

<script>
$(document).ready(function() {
  $('#body').load('ajax.php');
});
</script>
<div id="body"></div>

ajax.php

<?php
    echo "Hello, World!";
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消