jQuery Series 3 - Animation and ajax

Keywords: Javascript JQuery JSON Attribute

I. Display and Hide

hide(): Hidden in an HTML document, you set the css attribute display of an element to none

show(): Display. Show hidden elements. Set the display attribute of css to block or inline or other values other than none. It depends on the state before concealment. What is the state before hiding shows why it is

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            * {
                margin: 0px;
                padding: 0px;
            }       
            .box {
                width: 300px;
                height: 300px;
                background-color: pink;
                border: 1px dashed blue;
            }
        </style>
        <script src="libs/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function() {
                var $box = $(".box");
                $("button:eq(0)").click(function() {
                    //Display elements.  
                    $box.show();
                })
                $("button:eq(1)").click(function() {
                    //Hidden elements
                    $box.hide();
                })
            })
        </script>
    </head>
    <body>
        <div>
            <button>display</button>
            <button>hide</button>
        </div>
        <div class="box"></div>
    </body>
</html>

show and hide methods can also pass in parameters representing time. That is, from showing to hiding, or from hiding to showing the events that have passed. In this process, the transparency of elements will become larger or smaller, and the size will become smaller or larger.

Show (time), hide (time)

JQuery also provides three values: slow (for 600ms), nomal (for 400ms), and fast (for 200ms).

$box.show("slow");
$box.show(2000);  // 1000ms
$box.hide("slow");
$box.hide(2000);

Second, fade in and fade out

fadeIn() and fadeOut() fade in and out. Change only the transparency, not the size.

The parameters are consistent with show and hide

$box.fadeOut(2000);//Fade out
$box.fadeIn(2000); //Fade in

III. Expansion and Recycling

slideUp() and slideDown(). Put it away and spread it out. By changing the size of the element

$box.slideUp(1000);    //Retract
$box.slideDown(1000); //Open

IV. Other methods and attributes of animation

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            * {
                margin: 0px;
                padding: 0px;
            }       
            .box {
                width: 300px;
                height: 300px;
                background-color: pink;
                border: 1px dashed blue;
            }
        </style>
        <script src="libs/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function() {
                var $box = $(".box");
                $("button:eq(0)").click(function() {

                    //toggle() is used to switch the state of the element, if it is hidden, it will be displayed, if it is displayed, it will be hidden. You can replace hide and shouw
                    $box.toggle(2000);
                })
                $("button:eq(1)").click(function() {
                    //Used to replace fadeIn and fadeOut
                    $box.fadeToggle(2000);
                })
                $("button:eq(2)").click(function() {
                    //Used to replace slideUp and slideDown
                    $box.slideToggle(2000);
                })
                $("button:eq(3)").click(function() {
                    //Change the transparency to the specified transparency value. Change transparency only
                    $box.fadeTo(2000, 0.3)
                })
            })
        </script>
    </head>
    <body>
        <div>
            <button>Display and hide</button>
            <button>Fade in or out</button>
            <button>Expansion and contraction</button>
            <button>Change transparency to the specified value</button>
        </div>
        <div class="box"></div>
    </body>
</html>

V. Custom Animation

The above animation alone can not meet our needs, such as for a more complex animation effect, we need to customize the animation. Custom animation requires only one function: animate(params[, speed][,easing][, callback])

Parametric 1: A mapping pair of attributes and values containing styles. There can be multiple mappings. Must

Parametric 2: Optional. speed

Parametric 3: Animation operator (string). jquery defaults to only linear and swing. More complex needs third-party support.

Be sure to import jquery before animation operator plug-ins.

Parametric 4: Callback function. Optional. Represents a function that is executed after the animation has been executed.

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            * {
                margin: 0px;
                padding: 0px;
            }   
            .box {

                width: 300px;
                height: 300px;
                background-color: pink;
                border: 1px dashed blue;
                position: absolute;     
            }
        </style>
        <script src="libs/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function() {
                var $box = $(".box");
                $("button:eq(0)").click(function () {
                    //Custom Animation
                    $box.animate({left:"800px"}, 2000);

                });
                $("button:eq(1)").click(function () {
                    //Custom Animation
                    $box.animate({top:"500px"}, 2000);
                });
                $("button:eq(2)").click(function () {
                    //It constitutes an animation stream and executes in the order in which the animation is added.
                    $box
                    .animate({left:"800px"}, 500)
                    .animate({top:"500px"}, 2000)
                    .fadeOut();
                });
                $("button:eq(3)").click(function () {
                    //Simultaneous animation of multiple attributes
                    $box
                    .animate({left:"800px", top:"500px"}, 5000)
                });
            })
        </script>
    </head>
    <body>
        <div>
            <button>Towards the right</button>
            <button>down</button>
            <button>First right, then down</button>
            <button>Simultaneously right and down</button>
        </div>
        <div class="box"></div>
    </body>
</html>

6. Judging whether animation is executed or stopped

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            * {
                margin: 0px;
                padding: 0px;
            }       
            .box {          
                width: 300px;
                height: 300px;
                background-color: pink;
                border: 1px dashed blue;
                position: absolute;         
            }
        </style>
        <script src="libs/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function() {
                var $box = $(".box");
                $("button:eq(0)").click(function () {
                    $box.animate({left:"800px"}, 5000)
                    .animate({top:"600px"}, 6000);
                });
                $("button:eq(1)").click(function () {
                    //Determine whether the animation is executed
                    if($box.is(":animated")){
                        alert("Animation in progress");
                    }else{
                        alert("The animation was not executed");
                    }
                });
                $("button:eq(2)").click(function () {
                    //No parameters are passed in: to end the animation being executed and start executing the next animation in the animation queue.
//                  $box.stop();
                    /*stop There are two optional parameters:
                        Parametric 1: true/false true indicates that all animations in all animation queues are immediately cleared and the current animation is terminated. What has been done?
                                Where to stop. The default is false, which means stop the current animation and start the next one in the animation queue.
                        Parametric 2: true/false: Indicates whether the end of the current animation is reached directly at the end of the animation. True means to go directly to the end of the current animation, f
                                false,Represents maintaining the current state

                    */
                    $box.stop(true, true);
                });

            })
        </script>
    </head>
    <body>
        <div>
            <button>Start animation</button>
            <button>Determine whether the animation is executed</button>
            <button>Stop Animation</button>
        </div>
        <div class="box"></div>
    </body>
</html>

Seven, AJAX

Native JavaScript uses AJAX relatively cumbersome, and JQuery encapsulates AJAX to make it easier to use.

A total of six methods for AJAX are encapsulated and divided into three layers.

Bottom level: $. ajax()

Layer 2: $. load(), $. get(), $. post()

Layer 3: $. getScript(), $. getJson()

The second tier is the most widely used method.

7.1 load method

.load(url, [data], [callback])

url: To be loaded into the HTML web site.

Data: key/value data sent to the server. A string can also be accepted after jQuery 1.3. Optional

callback: callback function when loaded successfully. Optional

Note: By default, GET mode - automatically converts to POST mode when passing additional parameters

7.1.1 Load static HTML pages

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="libs/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function () {
                $("div button").click(function () {
                    //Load the specified url resource and insert the loaded content directly into the. content element. If there is content in. content, then
                  //It will cover the original content. Default get request. If a second parameter is added, the post request is automatically used
                    $("#content").load("html_data.html");
                })
            })
        </script>
    </head>
    <body>
        <div>
            <button>Use ajax Load the static page to the following div in</button>
        </div>
        <div id="content"></div>
    </body>
</html>

7.1.2 Screening for Additional Contents

Loaded data, we can also filter out the data we need, instead of filling all the elements.

Just use spaces behind the url to add our appropriate selector

//When the content is loaded, only the h1 element and the element whose id is # p are added to # content, while the others are not.
$("#content").load("html_data.html  h1,#p");

7.1.3 callback function

The last parameter of the load method is the callback function, which is always called back when the request is completed, regardless of whether the request is successful or not.

$("#content").load("html_data.html  h1,#p", function function_name (response,status,s) {
    //response - Contains the result data from the request
    //Status - Contains the status of the request ("success", "notmodified", "error", "timeout" or "parsererror")
    //xhr - Contains the XMLHttpRequest object
    alert("Loaded");
    console.log(response + "\n" + status + "\n" + xhr);
});

7.2 get method and post method

load is generally used to read static html pages (dynamic can also be used). If you want to easily transfer data to the server, use get or post more.

The load method is the method of the jQuery object, and the get and post methods are the global functions in JQuery, so you can call them directly with $. get() and $. post().

$.get(url, data, success(data,textStatus,xhr), dataType)

$.post(url, data, success(data, textStatus, xhr), dataType)

parameter describe
url Necessary. Specify which URL the request will be sent.
data Optional. Provide data to be sent to the server along with requests.
success(response,status,xhr) Optional. Specifies the function to run when the request succeeds. Additional parameters: response - contains the result data status from the request - contains the state xhr of the request - contains the XMLHttpRequest object
dataType Optional. Specify the data type of the expected server response. By default, jQuery will make intelligent judgments. Possible types: "xml", "html", "text", "script", "json", "jsonp"
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="libs/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function () {
                $("div button:eq(0)").click(function () {
                    $.get("html_data.html", {name:"zs", age:20}, function (data, status, xhr) {
                        $("#content1").html(data);
                    }, "html");
                })

                $("div button:eq(1)").click(function () {
                    $.post("html_data.jsp", {name:"zs", age:20}, function (data, status, xhr) {
                        $("#content2").html(data);
                    }, "html");
                })
            })
        </script>
    </head>
    <body>
        <div>
            <button>Use get Loading data</button>
            <button>Use post Loading data</button>
        </div>
        <div id="content1"></div>
        <div id="content2"></div>
    </body>
</html>

7.3 getScript method

Loading js files asynchronously and executing code in js files immediately after loading

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="libs/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function () {
                $("button").click(function () {
                    $.getScript("test.js", function () {
                        //callback
                    });
                })
            })
        </script>
    </head>
    <body>
        <div>
            <button>Load js file</button>
        </div>
        <div id="content1"></div>
        <div id="content2"></div>
    </body>
</html>

7.4 getJson method

Like the getScript method, it's just loaded data in json format

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="libs/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function () {
                $("button").click(function () {
                    $.getJSON("test.json", function (data) {
                        $("#name").html(data.name);
                        $("#pwd").html(data.pwd);
                    })
                })
            })
        </script>
    </head>
    <body>
        <div>
            <button>Display username and password</button>
        </div>
        <div>
            <div>
                Full name:<span id="name"></span>
            </div>
            <div>
                Password:<span id="pwd"></span>
            </div>
        </div>
    </body>
</html>

7.5 Ajax method

This method is an AJAX implementation at the bottom of JQuery, and the previous methods are all encapsulation of this method. There is only one parameter (object) in which all data about the request can be encapsulated.

$.ajax ( [ setting ] )

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="libs/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function () {
                $("button").click(function () {
                    var setting = {
                        url:"http://localhost:8020/%E9%AB%98%E7%BA%A7Day13_jquery%E5%8A%A8%E7%94%BB%E5%92%8CAjax/test.json",
                        type:"get",
                        //The data type requested is jsonp
                        dataType:"jsonp",
                        cache:false,
                        success:function(data) {
//                          foo(data);
                        },
                        //In the future, a parameter called back=?  
                         // callback=foo, jsonp is in foo(...)
                        jsonp:"callback",
                        jsonpCallback:"foo"
                    }
                    $.ajax(setting);
                })
                /*function foo (data) {
                    $("#name").html(data.name);
                    $("#pwd").html(data.pwd);
                }*/
            })

        </script>
    </head>
    <body>
        <div>
            <button>Use ajax Method</button>
        </div>
        <div>
            <div>
                //Full name:<span id="name"></span>
            </div>
            <div>
                //Password:<span id="pwd"></span>
            </div>
        </div>
    </body>
</html>

Posted by davidosullivan on Mon, 15 Apr 2019 13:03:33 -0700