JQuery_Ajax()基本應(yīng)用

源碼:
JS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>renwu26-3</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>
</head>
<style>
    .line{
        height: 30px;
        line-height: 30px;
        border: 1px solid grey;
        border-radius: 5px;
        padding: 10px;
        margin: 5px;
    }
    .button{
        padding: 5px;
        width: 80px;
        border-radius: 5px;
        margin: 5px;
        outline-style: none;
    }
    .hover{
        background-color: #6fc;
    }
</style>
<body>
    <div class="line">1</div>
    <div class="line">2</div>
    <button class="button">click</button>
    <script>
        /*
        接口
        1.url;
        2.get,post
        3.輸入:
        {
            start:2,
            length:6
        }
        4.輸出:
        {
            status:1 --OK
            data:[3,4,5,6,7,8]

            status:0 --ERROR
        }
        */
$('.button').on('click', function(){
        $.ajax(
            {
                url:'http://localhost/renwu26-3.php',
                dataType:'json',
                type:'get',
                data:{
                    start:$('.line').length,
                    len:6
                },
                success:function(json){
                    onSuccess(json);
                },
                error:function(){
                    onError();
                },
            }
        );
        function onSuccess(json){
            if(json.status==1){
                append(json.data);
            }
            else{
                alert('獲取失敗');
            }
        };
        function onError(){
            alert('鏈接失敗');
        };

        function append(arr){
            for(var i=0;i<arr.length;i++){
                $('.line:last').after('<div class="line">'+arr[i]+'</div>');
            }
        };
})

$('body').on('mouseenter', 'div', function(){
    $(this).addClass('hover');
    console.log(1);
})
$('body').on('mouseleave', 'div', function(){
    $(this).removeClass('hover');
})

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

php:

<?php
    // 后端 php 測試接口文件
    $start = $_GET['start']; //2
    $len = $_GET['len'];  //6 
    $items = array();
 
    for($i = 1; $i < $len; $i++){
        array_push($items, ($start+$i));
    }
    $ret = array('status'=>1, 'data'=>$items);

    //{status: 1, data: ['內(nèi)容1','內(nèi)容2','內(nèi)容3']}
    sleep(0.5);
    echo json_encode($ret);
?>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容