javaScript DOM JQuery AJAX

http://www.cnblogs.com/wupeiqi/articles/5369773.html

一 JavaScript

JavaScript是一门编程语言,浏览器内置了JavaScript语言的解释器,所以在浏览器上按照JavaScript语言的规则编写相应代码之,浏览器可以解释并做出相应的处理。

1.1 JavaScript代码存在形式

<!-- 方式一 -->
<script type="text/javascript" src="JS文件"></script>
 
<!-- 方式二 -->
<script type="text/javascript">
    Js代码内容
</script>

1.2 JavaScript代码存在位置

  • HTML的head中
  • HTML的body代码块底部(推荐)

由于Html代码是从上到下执行,如果Head中的js代码耗时严重,就会导致用户长时间无法看到页面,如果放置在body代码块底部,那么即使js代码耗时严重,也不会影响用户看到页面效果,只是js实现特效慢而已。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1{
            background: red;
        }
    </style>

    <script src="js/commons.js"></script>

    <script>
//        按照js规则解释
        function f1(){
            alert("f1")
        }
        f1();
        f2();


    </script>



</head>
<body>
<h1>Index</h1>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1{
            background: red;
        }
    </style>

</head>
<body>
<h1>Index</h1>
<h1>Index2</h1>
<h1>Index3</h1>
<h1>Index4</h1>


<script src="https://www.gstatic.com/og/_/js/k=og.og2.en_US.iF4jnkQuaf0.O/rt=j/t=zcms/m=def/exm=in,fot/d=1/ed=1/rs=AA2YrTv5-POC4Ks9GtGRdY2ywUWisqz7-Q"></script>
<script src="js/commons.js"></script>
<script>
//        按照js规则解释
    function f1(){
        alert("f1")
    }
    f1();
    f2();
</script>

</body>
</html>
/**
 * Created by hb on 2016/4/24.
 */
//commcons.js
function f2(){
    alert("f2")
}

1.3 变量

  • 全局变量
  • 局部变量

JavaScript中变量的声明是一个非常容易出错的点,局部变量必须一个 var 开头,如果未使用var,则默认表示声明的是全局变量

<script>
    name = "js";
//    var age = 18;
    var age = "20";
    age = parseInt(age)
    var qq = Number(1234);

    var v1="a", v2="b", v3="c"

    var num2 = "18.9"
    num2 = parseFloat(num2)
    console.log(num2, typeof(num2))
    console.log(age, typeof(age))

//    Number('123');
//    parseInt('456');

</script>

可以打开开发者工具 控制台的console来看及写

注:注释 // 或 /* */

1.4 基本数据类型

数字(Number)

var page = 111;
var age = Number(18);
var a1 = 1,a2 = 2, a3 = 3;
parseInt("1.2");
parseFloat("1.2");

字符串(String)

var name = "wupeiqi";
var name = String("wupeiqi");
var age_str = String(18);
 
常用方法:
    obj.trim()   //去掉空格
obj.trimLeft() //去掉左空格
obj.trimRight() //去掉右空格 obj.charAt(index) //根据下标查找字符 obj.substring(start,end) //根据下标查找子字符串 obj.indexOf(
char) //根据字符查找下标 obj.length //字符串长度

布尔(Boolean)

var status = true;
var status = false;
var status = Boolean(1==1)

数组(Array)

var names = ['alex', 'tony', 'eric']
var names = Array('alex', 'tony', 'eric')
 
常用方法:
    添加
        obj.push(ele)                   追加
        obj.unshift(ele)                最前插入
        obj.splice(index,0,'content')   指定索引插入
    移除
        obj.pop()                       数组尾部获取
        obj.shift()                     数组头部获取
        obj.splice(index,count)         数组指定位置后count个字符
      
    切片
        obj.slice(start,end)          
    合并
        newArray = obj1.concat(obj2)  
    翻转
        obj.reverse()
      
    字符串化
        obj.join('_')
    长度
        obj.length
 
 
字典
var items = {'k1': 123, 'k2': 'tony'}

var a= {k1:"v1", k2:"v2"}

var b = JSON.stringify(a)      //序列化 "{"k1":"v1","k2":"v2"}"
 
JSON.parse(b)        //反序列化 Object {k1: "v1", k2: "v2"}

undefined

undefined表示未定义值
var name;

null

null是一个特殊值

1.5 循环语句

var names = ["alex", "tony", "rain"];
 
 
for(var i in names){
console.log(i); //索引
}


// 数组:方式一 for(var i=0;i<names.length;i++){ console.log(i); console.log(names[i]); }

for(var i in names){
console.log(names[i]);
}
// 数组:方式二 for(var index in names){ console.log(index); console.log(names[index]); } var names = {"name": "alex", "age": 18}; // 字典:方式一 for(var index in names){ console.log(index); console.log(names[index]); } // while循环 while(条件){ // break; // continue; }

1.6 条件语句

//if条件语句
 
    if(条件){
 
    }else if(条件){
         
    }else{
 
    }
 
var name = 'alex';
var age = 1;
 
// switch,case语句
    switch(name){
        case '1':
            age = 123;
            break;
        case '2':
            age = 456;
            break;
        default :
            age = 777;
    }

1.7 异常处理

try{
 
}catch(e) {
 
}finally{
 
}

1.8 函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
//    普通函数
    function func1(arg){
        console.log(arg);
        return(arg);
    }
    var ff1 = func1("普通function")
    console.log(ff1)


//    匿名函数
    var ff = function(arg){
        console.log("匿名function", arg);

    }
    ff("qq");

//    自执行函数    ()()
(function(arg){ console.log(arg); })("456") </script> </body> </html>

1.9 面向对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
//    JavaScript面向对象的用js的原型实现继承
    function Foo(name, age){
        this.Name = name;
        this.Age = age;
        this.Func = function(arg){
            return(this.Name + arg);
        }

    }

//    实例化
    var obj = new Foo("laonanhai", 18);
    console.log(obj.Name);
    console.log(obj.Age);
    var res = obj.Func('sb');
    console.log(res);
    
</script>

</body>
</html>

二 Dom

文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口。它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式。我们最为关心的是,DOM把网页和脚本以及其他的编程语言联系了起来。DOM属于浏览器,而不是JavaScript语言规范里的规定的核心内容。全部html封装到了document对象中。

注:一般说的JS让页面动起来泛指JavaScript和Dom

<h1>index</h1>
<h1>index</h1>

targs = document.getElementsByTagName("h1");
targs[0].innerText = "123";

2.1 选择器

document.getElementById('id');
document.getElementsByName('name');
document.getElementsByTagName('tagname');
var lis2 = document.getElementsByClassName('c1');

2.2、内容

innerText
innerHTML
 
var obj = document.getElementById('nid')
obj.innerText                       # 获取文本内容
obj.innerText = "hello"             # 设置文本内容
obj.innerHTML                       # 获取HTML内容
obj.innerHTML = "<h1>asd</h1>"      # 设置HTML内容
 
 
特殊的:
    input系列
    textarea标签
    select标签
 
    value属性操作用户输入和选择的值

示例:点击按键,数字加1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <div id="num">1</div>
    <input type="button" value="+1" onclick="Add();">
</div>


<script>
    function Add(){
        /*
        alert("123");
        1 找到num
        2 获取内容
        3 自增
        */
        var nid = document.getElementById('num');
        var cont = nid.innerText;
        cont = parseInt(cont);
        cont++;
        nid.innerText = cont;
    }

</script>

</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1{
            color: red;
        }
    </style>
    
</head>
<body>
    <div>
        <div id="n1">c1</div>
        <a href="http://jd.com">购物</a>
    </div>

    <ul>
        <li>123</li>
        <li>123</li>
        <li>123</li>
        <li>123</li>
        <li>123</li>
    </ul>

    <div>
        <div class="c1">111</div>
        <div class="c1">222</div>
        <div class="c1">333</div>
    </div>

    <form>
        <p>用户名:<input type="text" name="username" value="admin"></p>
        <p>密码:<input type="password" name="pwd" value="adminpwd"></p>
        <p><input type="submit"></p>
    </form>

    <script type="text/javascript">
        var nid = document.getElementById('n1');
        nid.innerText = "nnn1";

        var lis = document.getElementsByTagName('li');
        for (var i in lis){
            var item = lis[i];
            item.innerText = i;
        }

        var lis2 = document.getElementsByClassName('c1');
//        console.log(lis2);
        for (var i in lis2){
            var item = lis2[i];
            item.innerText = i;
        }

        for (var i = 0; i < lis2.length; i++){
            console.log(i);
        }

        var username = document.getElementsByName("username")[0];
        var pwd = document.getElementsByName("pwd")[0];
        console.log(username.value, pwd.value);


    </script>

</body>
</html>

dom文本操作:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="n1">
        goood study
        <h1>day day up</h1>
    </div>

    <h1>特殊的:value</h1>
    <h3><input type="button" value="获取值" onclick="GetValue2();"></h3>
    <input id="n2" type="text">

    <h3><input type="button" value="获取值" onclick="GetValue3();"></h3>
    <select id="n3" name="city">
        <option value="1">上海</option>
        <option value="2">北京</option>
        <option value="3">广州</option>
    </select>

    <h3><input type="button" value="获取值" onclick="GetValue4();"></h3>
    <textarea id="n4">ttt</textarea>

    <script>
        var n1id = document.getElementById('n1');
        console.log(n1id.innerText);
        console.log(n1id.innerHTML);

        function GetValue2(){
            var nid = document.getElementById('n2');
            alert(nid.value);
            nid.value = "";
        }

        function GetValue3(){
            var nid = document.getElementById('n3');
            alert(nid.value);
            nid.value = "2";
        }

        function GetValue4(){
            var nid = document.getElementById('n4');
            alert(nid.value);
            nid.value = "go go go ...";
        }


    </script>

</body>
</html>

 

 

DOM事件和搜索框示例

(光标聚焦时显示 清除提示 请输入关键字,光标失去焦点时且没有输入内容时再提示 请输入关键字)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <input type="text" id="search" value="请输入关键字" onfocus="Focus();" onblur="Blur();">


    <script>
        function Focus(){
            var nid = document.getElementById('search');
            var cont = nid.value;
            if (cont == "请输入关键字"){
                nid.value = "";
            }
        }

        function Blur(){
            var nid = document.getElementById('search');
            var cont = nid.value;
            if (! cont.trim()){
                nid.value = "请输入关键字";
            }
        }

    </script>

</body>
</html>

2.3 创建标签

方式一:
    var obj = document.createElement('a');
    obj.href = "http://www.etiantian.org";
    obj.innerText = "老男孩";
 
    var container = document.getElementById('container');
    //container.appendChild(obj);
    //container.insertBefore(obj, container.firstChild);
    //container.insertBefore(obj, document.getElementById('hhh'));
 
方式二:
    var container = document.getElementById('container');
    var obj = "<input  type='text' />";
    container.innerHTML = obj;
    // 'beforeBegin', 'afterBegin', 'beforeEnd',  'afterEnd'
    //container.insertAdjacentHTML("beforeEnd",obj);

 

创建标签示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <!--自定义事件执行并返回false,则默认事件就不再执行-->
    <a href="http://www.etiantian.org" onclick="AddElement();">添加</a>
    <a href="http://www.etiantian.org" onclick="return AddElement2();">添加2</a>

    <br> <br>
    <a href="http://www.etiantian.org" onclick="return AddElement3();">添加3</a>
    <div id="container"></div>
    <br> <br>
    <a href="http://www.etiantian.org" onclick="return AddElement4();">添加4</a>
    <div id="container2"></div>
    <br> <br>
    <a href="http://www.etiantian.org" onclick="return AddElement5();">添加5</a>
    <div id="container3"></div>


    <script>
        function AddElement(){
            alert("123");
        }

        function AddElement2(){
            alert("339");
            return false;
        }

        function  AddElement3(){
            var nid = document.getElementById('container');
            var tag = "<input type='text'>";
            nid.innerHTML = tag;
            return false;
        }

        function  AddElement4(){
            var nid = document.getElementById('container2');
            var tag = "<input type='text'>";
            // 'beforeBegin', 'afterBegin', 'beforeEnd',  'afterEnd'
            container2.insertAdjacentHTML("afterBegin", tag);
            return false;
        }

        function  AddElement5(){
//            添加 a标签
            var createObj = document.createElement('a');
            createObj.href = "http://www.baidu.com";
            createObj.innerText = "度娘 ";

            var nid = document.getElementById('container3');
//            nid.innerHTML = createObj;
            nid.appendChild(createObj);
            return false;
        }

    </script>

</body>
</html>

2.4、标签属性

var obj = document.getElementById('container');
固定属性
    obj.id
    obj.id = "nid"
    obj.className
    obj.style.fontSize = "88px";
 
自定义属性
    obj.setAttribute(name,value)
    obj.getAttribute(name)
    obj.removeAttribute(name)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="container" name="xxx" sb="oo" style="font-size: 14px; color: red;">
    SSSBBB
</div>

</body>
</html>

2.5、提交表单

document.geElementById('form').submit()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <h3>submit提交</h3>
    <form action="https://www.sogou.com/web" method="get">
        <input type="text" name="query">
        <input type="submit" value="提交" >
    </form>
</div>

<br><br>

<div>
    <h3>div=其他标签提交改造</h3>
   <form id="form1" action="https://www.sogou.com/web" method="get">
       <input type="text" name="query">
       <!--<input type="text" name="query">-->
       <div onclick="Sub();" style="cursor: pointer; border: 1px solid #333; background-color: #999;40px;">提交</div>
    </form>

</div>

<script type="text/javascript">
    function Sub(){
        document.getElementById("form1").submit();

    }

</script>

</body>
</html>

检查表单内容是否为空,为空则弹出提示信息,不执行提交

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    <form action="https://www.sogou.com/web" method="get">
        <input type="text" name="query">
        <input type="submit" value="提交" onclick="return Mysubmit();">
    </form>

</div>

<script>
    function Mysubmit(){
        var q = document.getElementsByName("query")[0];
        if (q.value.trim()){
            return true;
        }else{
            alert("请输入内容")
            return false;
        }

    }

</script>

</body>
</html>

2.6、事件

特殊的:

window.onload = function(){}
        //jQuery:$(document).ready(function(){})
        //onload是所有DOM元素创建、图片加载完毕后才触发的。而ready则是DOM元素创建完毕后触发的,不等图片加载完毕。图片还么有渲染,就可以进行事件的执行。

2.7 其他功能 

console.log()
alert()
confirm()
 
// URL和刷新
location.href
location.href = "url"  window.location.reload()
 
// 定时器
setInterval("alert()",2000);   
clearInterval(obj)
setTimeout();   
clearTimeout(obj)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="button" value="上来呀" onmousemove="Myconfirm();">
    <script>
        function Myconfirm(){
            var res = confirm("请确定或取消");
            console.log(res);
        }
    </script>

</body>
</html>

dom定时器和跑马灯

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎领取莅临指导</title>
</head>
<body>

<input type="button" value="title跑马灯停下来" onclick="StopInterval();">

<script>
//    setInterval("操作", 时间间隔)
//    setInterval("alert('bbbb')", 2000);
    obj1 = setInterval("Func()", 1000)

//    执行总时间
//    obj1 = setTimeout("Func()", 1000);

    function Func(){
        var text = document.title;
        var firstChar = text[0];
        var subText = text.substring(1, text.length);
        var newTitle = subText + firstChar;
        document.title = newTitle;
    }

    function StopInterval(){
        clearInterval(obj1);
    }
</script>

</body>
</html>

搜索框:

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8' />
        <title></title>

        <style>
            .gray{
                color:gray;
            }
            .black{
                color:black;
            }
        </style>
        <script type="text/javascript">
            function Enter(){
               var id= document.getElementById("tip");
               id.className = 'black';
               if(id.value=='请输入关键字'||id.value.trim()==''){
                    id.value = '';
               }
            }
            function Leave(){
                var id= document.getElementById("tip")
                var val = id.value;
                if(val.length==0||id.value.trim()==''){
                    id.value = '请输入关键字';
                    id.className = 'gray';
                }else{
                    id.className = 'black';
                }
            }
        </script>
    </head>
    <body>
        <input type='text' class='gray' id='tip' value='请输入关键字' onfocus='Enter();'  onblur='Leave();'/>
    </body>
</html>

 三 JQuery

jQuery是一个兼容多浏览器的javascript库,核心理念是write less,do more(写得更少,做得更多),对javascript进行了封装,是的更加便捷的开发,并且在兼容性方面十分优秀。

http://www.php100.com/manual/jquery/

3.1 选择器和筛选器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="n1">11</div>
<div>22</div>
<div>33</div>

<div class="c1">55</div>
<div class="c1">66</div>
<a></a>
<span id="n2"></span>


<div id="n3">
    <div>
        <div class="c3">
            <span>
                <a class="c4">aaaaaa</a>
            </span>
        </div>
    </div>
    <span>span span span</span>
</div>

<script src="js/jquery-2.2.3.js"></script>

<script>
    /*
    1 获取标签
    2 修改
    $ <==> jQuery
    #表示ID
    .表示class
    */
//    ID选择器
    $("#n1").text("123");
//    下面这个也是可以的
//    jQuery("#n1").text("abc");
//    标签选择器
//    $("div").text("xxxx");
////    class选择器
//    $(".c1").text("yyyy");
////    组合选择器
//    $(".c1, a, #n2").text("OK ");
//  层级选择器
//    $("#n3 div .c3 span a").text("层级选择器");
//    $(".c3 a").text("层级选择器");  与 $("#n3 div .c3 span a").text("层级选择器"); 是一样的
//    $(".c3 a").text("层级选择器");
    $(".c4").text("层级选择器333");




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

实例: jquery左侧菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .menu{
            float: left;
            width: 30%;
            height:600px;
            background-color: antiquewhite;
        }
        
        .content{
            float: left;
            width:70%;
            height:600px;
            background: blue;
        }

        .title{
            background-color: black;
            color: white;
            height:50px;
            line-height: 50px;
            cursor:pointer;
        }

        .hidden{
            display: none;
        }

    </style>
    <script src="js/jquery-2.2.3.js"></script>
</head>
<body>

<div>
    <div class="menu">
        <div class="item">
            <div class="title" onclick="Func(this);">菜单一</div>
            <div class="body">
                <div>1.1</div>
                <div>1.2</div>
                <div>1.3</div>
            </div>
        </div>

        <div class="item">
            <!--this指本标签-->
            <div class="title" onclick="Func(this);">菜单二</div>
            <div class="body hidden">
                <div>2.1</div>
                <div>2.2</div>
                <div>2.3</div>
            </div>
        </div>

        <div class="item">
            <div class="title" onclick="Func(this);">菜单三</div>
            <div class="body hidden">
                <div>3.1</div>
                <div>3.2</div>
                <div>3.3</div>
            </div>
        </div>

    </div>

    <div class="content"></div>

</div>

<script>
    function Func(me){
        $(me).next().removeClass("hidden");
        $(me).parent().siblings().find(".body").addClass("hidden");
    }

</script>

</body>
</html>

 Tab菜单:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tab菜单1</title>

    <style>
        .tab-box .box-menu{
            background-color: #ddd;
            border: 1px solid #ddd;
            height: 33px;
            line-height:33px;
        }

        .tab-box .box-body {
            border: 1px solid #ddd;
        }
        .hide{
            display: none;
        }

        .box-menu a{
            cursor: pointer;
            border-right: 1px solid #999;
            padding: 10px;
        }
        
        .current{
            background: white;
            color: black;
            border-top:2px solid red;
        }

    </style>
    <script src="js/jquery-2.2.3.js"></script>
</head>
<body>

    <div class="tab-box">
        <div class="box-menu">
            <!--所有菜单-->
            <a tabbutton="c1" class="current" onclick="ChangeTab(this);">菜单一</a>
            <a tabbutton="c2" onclick="ChangeTab(this);">菜单二</a>
            <a tabbutton="c3" onclick="ChangeTab(this);">菜单三</a>
        </div>
        <div class="box-body">
            <!--所有内容-->
            <div id="c1">内容一</div>
            <div id="c2" class="hide">内容二</div>
            <div id="c3" class="hide">内容三</div>
        </div>

    </div>

<script>
    function ChangeTab(ths){
    /*
    * 获取当前点击的标签 $(ths)
    * 获取当前标签的属性tabbutton对应的值
    *值 $("xx") 显示,其他兄弟隐藏
    * */
        $(ths).addClass("current").siblings().removeClass("current")
        var contendID = $(ths).attr("tabbutton");
        var temp = "#" + contendID;
        $(temp).removeClass("hide").siblings().addClass("hide");


    }
</script>

</body>
</html>

全选 、取消、反选及循环

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
</head>
<body>

<div>
    <input type="button" value="全选" onclick="SelectAll();">
    <input type="button" value="取消" onclick="ClearAll();">
    <input type="button" value="反选" onclick="ReverseAll();">

</div>

<div>
    <table border="1">
        <tr>
            <td><input type="checkbox"></td>
            <td>123</td>
            <td>123</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>123</td>
            <td>123</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>123</td>
            <td>123</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>123</td>
            <td>123</td>
        </tr>

    </table>

</div>

<script>
    function SelectAll(){
        $("table :checkbox").prop("checked",true);
    }

    function ClearAll(){
        $("table :checkbox").prop("checked",false);
    }

    function ReverseAll(){
        $("table :checkbox").each(function(){       //jQuery的另一种循环方式,即通过.each()
            //每个循环都执行该方法体
            //$(this) 表示当前循环的元素
            var isChecked = $(this).prop("checked");
            if (isChecked){
                $(this).prop("checked", false);
            }else{
                $(this).prop("checked", true);
            }
        })

        var userList = [11, 22, 33, 44];
        $.each(userList, function(i, item){
            console.log(i, item);       //打印userlist 下标及 item.若userList为字典,则i 表示key, item表示value
        })
        //jQuery循环的一种,把要循环的内容放入each()的第一个参数

        for (var i in userList){
            console.log(i, userList[i]);        // i为下标
        }

    }
</script>

</body>
</html>

html行编辑、全选、取消、反选

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全选、反选、编辑</title>

    <link href="css/common.css" rel="stylesheet">

    <script src="js/jquery-2.2.3.js"></script>
    <script src="js/hw4.js" type="text/javascript"></script>
</head>
<body>

<div class="select_div">
    <div class="selectButton">
        <input type="button" value="全选" onclick="SelectAll();">
    </div>
    <div class="selectButton">
        <input type="button" value="反选" onclick="SelectInvert();">
    </div>
    <div class="selectButton">
        <input type="button" value="取消" onclick="Cancel();">
    </div>
    <div id="edit_back" class="enterEdit">
        <div class="enterEdit2" onclick="Edit();">进入编辑模式</div>
    </div>
    <div class="clear_both"></div>

</div>

<div>
    <form>
        <div class="tab">
            <table id="tab1" border="1">
                <!--表头-->
                <thead>
                    <tr>
                        <th>选择</th>
                        <th>主机名</th>
                        <th>端口</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><input type="checkbox"></td>
                        <td>db1</td>
                        <td>80</td>
                        <td>在线</td>
                    </tr>
                    <tr>
                        <td><input type="checkbox"></td>
                        <td>db2</td>
                        <td>80</td>
                        <td>下线</td>
                    </tr>
                    <tr>
                        <td><input type="checkbox" checked="checked"></td>
                        <td>zabbix</td>
                        <td>8080</td>
                        <td>在线</td>
                    </tr>
                </tbody>

            </table>

        </div>
    </form>
</div>


<!--<script>-->
    <!--//选中所有checkbox-->
    <!--function SelectAll(){-->
        <!--$("#tab1").find("input[type='checkbox']").prop("checked", true);-->
    <!--}-->

    <!--//取消选中所有checkbox-->
    <!--function Cancel(){-->
        <!--$("#tab1").find("input[type='checkbox']").prop("checked", false);-->
    <!--}-->

    <!--//反选checkbox-->
    <!--function SelectInvert(){-->
        <!--$("input[type='checkbox']").prop("checked", function( i, val ) {-->
            <!--//console.log(val);-->
            <!--return !val;-->
        <!--});-->
    <!--}-->

    <!--function Edit(){-->
        <!--$("#tab1").find(":checkbox:checked").each(function(){-->
           <!--$(this).parent().siblings().each(function(i){-->
               <!--var val = $(this).text();-->
               <!--$(this).text("");-->
               <!--var add_input = "";-->


               <!--if (i == "2"){       //td第三列 即状态-->
                   <!--if (val == "在线"){-->

                        <!--add_input = '<select name="status"><option value=1 selected="selected">在线</option><option value=2>下线</option></select>';-->
                    <!--}else{-->
                        <!--add_input = '<select name="status"><option value=2>在线</option><option value=2 selected="selected">下线</option></select>';-->
                   <!--}-->
               <!--}else{-->
                   <!--add_input = '<input type="text" value="' + val + '">';-->
               <!--}-->
               <!--//插入input标签或select标签-->
               <!--$(this).html(add_input);-->
           <!--});-->

        <!--});-->
    <!--}-->


<!--</script>-->



</body>
</html>



<!--  JS部分 -->

/**
* Created by hb on 2016/4/29.
*/

//选中所有checkbox
function SelectAll(){
    $("#tab1").find("input[type='checkbox']").prop("checked", true);
}

//取消选中所有checkbox
function Cancel(){
    $("#tab1").find("input[type='checkbox']").prop("checked", false);
}

//反选checkbox
function SelectInvert(){
    $("input[type='checkbox']").prop("checked", function( i, val ) {
        //console.log(val);
        return !val;
    });
}

function Edit(){
    //改变 编辑按钮标签背景颜色
    $("#edit_back").removeClass("enterEdit");
    $("#edit_back").addClass("enterEditOnclick");

    $("#tab1").find(":checkbox:checked").each(function(){
       $(this).parent().siblings().each(function(i){
           var val = $(this).text();
           $(this).text("");
           var add_input = "";


           if (i == "2"){       //td第三列 即状态
               if (val == "在线"){

                    add_input = '<select name="status"><option value=1 selected="selected">在线</option><option value=2>下线</option></select>';
                }else{
                    add_input = '<select name="status"><option value=2>在线</option><option value=2 selected="selected">下线</option></select>';
               }
           }else{
               add_input = '<input type="text" style=" 116px" value="' + val + '">';
           }
           //插入input标签或select标签
           $(this).html(add_input);
       });

    });
}

模态对话框,文档处理(html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="css/common.css" rel="stylesheet">

    <script src="js/jquery-2.2.3.js"></script>
</head>
<body>

<div class="tab">
    <table border="1">
        <!--表头-->
        <thead>
            <tr>
                <th>主机</th>
                <th>IP</th>
                <th>端口</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>web1</td>
                <td>172.16.1.10</td>
                <td>80</td>
                <td class="tab_td" onclick="ClickEdit(this);">编辑</td>
            </tr>
            <tr>
                <td>web2</td>
                <td>172.16.1.11</td>
                <td>80</td>
                <td class="tab_td" onclick="ClickEdit(this);">编辑</td>
            </tr>
            <tr>
                <td>web3</td>
                <td>172.16.1.12</td>
                <td>80</td>
                <td class="tab_td" onclick="ClickEdit(this);">编辑</td>
            </tr>
        </tbody>

    </table>

</div>

<div id=editTab class="form1 hidden">
    <form action="http://127.0.0.1:8080/" method="post">
        <div id="edit">
            <p>主机名:<input id="host"  type="text" class=""></p>
            <p>IP:<input id="ip" type="text" class=""></p>
            <p>端口:<input id="port" type="text" class=""></p>
        </div>
        <div>
            <input type="submit" value="提交" onclick="return checkSubmit();">
            <input type="button" value="取消" onclick="cancleEdit()">
        </div>
    </form>
</div>


<script>
    function checkSubmit(){
        var sub_ok = true;
        $(":text").each(function(){
            var input_val = $(this).val().trim()
            if (input_val.length == 0){
//                $(this).css("border-color", "red");
                $(this).addClass("input_empty");
               sub_ok = false
            }else{
//                $(this).css("border-color", "green");
                $(this).addClass("input_not_empty");
            }
        });
        return sub_ok;
    }

    function ClickEdit(me){
        $("#editTab").removeClass("hidden");
        var tab_list = [];
        /*
        //遍历同辈的td值,并追加到tab_list列表
        $.each($(me).prevAll(), function(i){
            var item = $(me).prevAll()[i];
            var content = $(item).text();
            tab_list.push(content);
        });
        //反转 tab_list
        tab_list = tab_list.reverse();
*/

        //也可用siblings获取同胞的td值
        $.each($(me).siblings(), function(i){
            var item = $(me).siblings()[i];
            var content = $(item).text();
            tab_list.push(content);
        });


        $("#host").val(tab_list[0]);
        $("#ip").val(tab_list[1]);
        $("#port").val(tab_list[2]);


    }

    function cancleEdit(){
       $("#editTab").addClass("hidden");
    }

</script>

</body>
</html>



//CSS:
th{
     120px;

}

.form1{
    position: fixed;
    /*top:20%;*/
    /*right: 20%;*/
    top: 0;
    right:0;
    bottom: 0;
    left: 0;
    margin: auto;
    background-color:#999;
    600px;
    height:500px;
    z-index: 1000;
}

.input_empty{
    border: 1px solid red;
}

.input_not_empty{
    border: 1px solid green;
}

.tab_td{
    cursor: pointer;
}

.hidden{
    display: none;
}

.tab{
    z-index: 100;
}

返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>返回顶部</title>
    <style>
        .goTop, .divGoTop{
            position: fixed;
            right: 10px;
            bottom: 10px;
            width: 80px;
            height: 80px;
            border: 1px solid #f59e00;
            cursor: pointer;
        }
        .divGoTop{
            bottom: 150px;
        }
        
        .hide{
            display: none;
        }
    </style>

    
</head>
<body>

<div style="height: 2000px; background-color: #ddd;">顶部
    <div id="nid" style="background-color: red; height: 200px; overflow: scroll">
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
    </div>

</div>

<div class="goTop hide" onclick="GoTop();">
    <p style="line-height: 80px ;text-align: center; margin:auto; top: 0;right: 0; bottom: 0; left: 0">返回顶部</p>
</div>

<div class="divGoTop" onclick="DivGoTop();">
    <p style="line-height: 80px ;text-align: center; margin:auto; top: 0;right: 0; bottom: 0; left: 0">DIV顶部</p>
</div>

<script src="js/jquery-2.2.3.js"></script>

<script>
    function GoTop(){
        $(window).scrollTop(0);
    }

    function DivGoTop(){
        $("#nid").scrollTop(0);
    }
    
    window.onscroll = function(){
        var scrollTopVal = $(window).scrollTop();
        if (scrollTopVal > 100){
            $(".goTop").removeClass("hide");
        }else{
            $(".goTop").addClass("hide");
        }
    }
    
</script>

</body>
</html>

滚动菜单

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>

        body{
            margin: 0px;
        }
        img {
            border: 0;
        }
        ul{
            padding: 0;
            margin: 0;
            list-style: none;
        }
        .clearfix:after {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }

        .wrap{
            width: 980px;
            margin: 0 auto;
        }

        .pg-header{
            background-color: #303a40;
            -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            box-shadow: 0 2px 5px rgba(0,0,0,.2);
        }
        .pg-header .logo{
            float: left;
            padding:5px 10px 5px 0px;
        }
        .pg-header .logo img{
            vertical-align: middle;
            width: 110px;
            height: 40px;

        }
        .pg-header .nav{
            line-height: 50px;
        }
        .pg-header .nav ul li{
            float: left;
        }
        .pg-header .nav ul li a{
            display: block;
            color: #ccc;
            padding: 0 20px;
            text-decoration: none;
            font-size: 14px;
        }
        .pg-header .nav ul li a:hover{
            color: #fff;
            background-color: #425a66;
        }
        .pg-body{

        }
        .pg-body .catalog{
            position: absolute;
            top:60px;
            width: 200px;
            background-color: #fafafa;
            bottom: 0px;
        }
        .pg-body .catalog.fixed{
            position: fixed;
            top:10px;
        }

        .pg-body .catalog .catalog-item.active{
            color: #fff;
            background-color: #425a66;
        }

        .pg-body .content{
            position: absolute;
            top:60px;
            width: 700px;
            margin-left: 210px;
            background-color: #fafafa;
            overflow: auto;
        }
        .pg-body .content .section{
            height: 500px;
        }
    </style>
</head>
<body>

    <div class="pg-header">
        <div class="wrap clearfix">
            <div class="logo">
                <a href="#">
                    <img src="https://concat.lietou-static.com/pics/pc/p/beta2/images/logo.png">
                </a>
            </div>
            <div class="nav">
                <ul>
                    <li>
                        <a  href="#">首页</a>
                    </li>
                    <li>
                        <a  href="#">功能一</a>
                    </li>
                    <li>
                        <a  href="#">功能二</a>
                    </li>
                </ul>
            </div>

        </div>
    </div>
    <div class="pg-body">
        <div class="wrap">
            <div class="catalog">
                <div class="catalog-item" auto-to="function1"><a>第1章</a></div>
                <div class="catalog-item" auto-to="function2"><a>第2章</a></div>
                <div class="catalog-item" auto-to="function3"><a>第3章</a></div>
            </div>
            <div class="content">

                <div menu="function1" class="section">
                    <h1>第一章</h1>
                </div>
                <div menu="function2" class="section">
                    <h1>第二章</h1>
                </div>
                <div menu="function3" class="section">
                    <h1>第三章</h1>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript" src="js/jquery-2.2.3.js"></script>
    <script type="text/javascript">

        window.onscroll = function(){
            //滚动的高度
            var ws = $(window).scrollTop();
            if (ws > 50){
                $(".catalog").addClass("fixed");
            }else{
                $(".catalog").removeClass("fixed");
            }

            $(".content").children().each(function(){
                var offs = $(this).offset();
                var offTop = offs.top;
                //当前标签离顶部高度 < 滚动高度  且
                //当前标签离顶部高度 + 当前标签的高度  > 滚动高度
                var total = offTop + $(this).height();
                if (ws > offTop && total > ws){
                    //如果滚动条到了底部,最后一个菜单增大
                    //滚动的高度 + window的高度 = 文档的高度,说明滚动条到了底部
                    //  :last  最后一个
                    if ($(window).scrollTop()+$(window).height() == $(document).height()){
                        $(".catalog").children(":last").css("fontSize", "48px").siblings().css("fontSize", "12px");
                    }else{
                        var t = $(this).attr("menu");
                        var target = 'div[auto-to="' + t + '"]';
                        $(".catalog").children(target).css("fontSize", "48px").siblings().css("fontSize", "12px");
                        return;
                    }
                }

            });
        };


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

jQuery事件1:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
    </ul>
</div>

<script src="js/jquery-2.2.3.js"></script>

<script>

    //给li标签绑定事件
    $("li").click(function(){
        var temp = $(this).text();
        alert(temp);
    });
    //当前文档树准备就绪
    $(document).ready(function(){

    });

    // 等价上面的  当前文档树准备就绪
    $(function(){

    });


</script>

</body>
</html>

jQuery事件2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    <input type="button" value="添加" onclick="AddContent();">
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
    </ul>
</div>

<script src="js/jquery-2.2.3.js"></script>

<script>

    //当前文档树准备就绪
    $(function(){
        //给li标签绑定事件
        $("li").click(function(){
            var temp = $(this).text();
            alert(temp);
        });

        /* 与上面的是一样的
        $("li").bind("click", function(){
            var temp = $(this).test();
            alert(temp);
        });
        */
    });

    function AddContent(){
        $("ul").append("<li>9</li>");
        $("li:last").click(function(){
            var temp = $(this).text();
            alert(temp);
        });
    }

</script>

</body>
</html>

jQuery事件3:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    <input type="button" value="添加" onclick="AddContent();">
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
    </ul>
</div>

<script src="js/jquery-2.2.3.js"></script>

<script>

    //当前文档树准备就绪
    $(function(){
        //给li标签绑定事件
        /*
        $("li").click(function(){
            var temp = $(this).text();
            alert(temp);
        });
        */

        //delegate() 委托事件,即在动作的时候才绑定件事
        $("ul").delegate("li", "click", function(){
            var temp = $(this).text();
            alert(temp);
        });
    });


    function AddContent(){
        $("ul").append("<li>9</li>");
//        $("li:last").click(function(){
//            var temp = $(this).text();
//            alert(temp);
//        });
    }


</script>

</body>
</html>

拖动面板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>拖动面板</title>
</head>
<body>
<div style="border: 1px solid #ddd; 600px;position: absolute;">
    <div id="title" style="background-color: black; height: 40px; color: white;">
        标题
    </div>
    <div style="height: 300px;">
        内容
    </div>
</div>

<script src="js/jquery-2.2.3.js"></script>
<script>
    //页面加载完成之后自动执行
    $(function(){
        $("#title").mouseover(function(){
           $(this).css("cursor", "move");
        }).mousedown(function(e){       // e ==>封装事件的对象
//            console.log($(this).offset())
            var _event = e || window.event      //为了兼容,有些浏览器不支持 e
            //原始鼠标横纵坐标位置
            var ord_x = _event.clientX;
            var ord_y = _event.clientY;

            var parent_left = $(this).parent().offset().left;
            var parent_top = $(this).parent().offset().top;

            $(this).bind("mousemove", function(e){
                var _new_event = e || window.event;
                var new_x = _new_event.clientX;
                var new_y = _new_event.clientY;

                var x = parent_left + (new_x - ord_x);
                var y = parent_top + (new_y - ord_y);

                $(this).parent().css("left", x+"px");
                $(this).parent().css("top", y+"px");

            });

        }).mouseup(function(){      //鼠标弹起时取消 标题的 mousemove 事件
            $(this).unbind("mousemove");
        });

    });

</script>

</body>
</html>

返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>返回顶部</title>
    <style>
        .goTop, .divGoTop{
            position: fixed;
            right: 10px;
            bottom: 10px;
            width: 80px;
            height: 80px;
            border: 1px solid #f59e00;
            cursor: pointer;
        }
        .divGoTop{
            bottom: 150px;
        }
        
        .hide{
            display: none;
        }
    </style>

    
</head>
<body>

<div style="height: 2000px; background-color: #ddd;">顶部
    <div id="nid" style="background-color: red; height: 200px; overflow: scroll">
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
        <p>~~~~~~~~~~~~~~~~~</p>
    </div>

</div>

<div class="goTop hide" onclick="GoTop();">
    <p style="line-height: 80px ;text-align: center; margin:auto; top: 0;right: 0; bottom: 0; left: 0">返回顶部</p>
</div>

<div class="divGoTop" onclick="DivGoTop();">
    <p style="line-height: 80px ;text-align: center; margin:auto; top: 0;right: 0; bottom: 0; left: 0">DIV顶部</p>
</div>

<script src="js/jquery-2.2.3.js"></script>

<script>
    function GoTop(){
        $(window).scrollTop(0);
    }

    function DivGoTop(){
        $("#nid").scrollTop(0);
    }
    
    window.onscroll = function(){
        var scrollTopVal = $(window).scrollTop();
        if (scrollTopVal > 100){
            $(".goTop").removeClass("hide");
        }else{
            $(".goTop").addClass("hide");
        }
    }
    
</script>

</body>
</html>

jQuery扩展

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script src="js/jquery-2.2.3.js"></script>
<script>
//    jQuery.extend()     <==>  $.extend
    //扩展jQuery对象本身
    jQuery.extend({
        login:function(){
            return "Login OK"
        },
        uncheck: function() {
            return this.each(function() { this.checked = false; });
        }
    });

    var res = $.login();
    alert(res);

    //扩展jQuery对象(通常用来制作插件)
    $.fn.extend({
        exit:function(){
            return "Exit OK"
        }
    });

    var res2 = $("#nid").exit();
    alert(res2);


</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script src="js/jquery-2.2.3.js"></script>
<!--<script src="js/JQExtend.js"></script>-->
<script src="js/JQExtend2.js"></script>
<script>
    var res = $.login();
    alert(res);

    var res2 = $("#nid").exit();
    alert(res2);


</script>

</body>
</html>


<!-- JQExtend.js -->
/**
 * Created by hb on 2016/5/10.
 */
//    jQuery.extend()     <==>  $.extend
//扩展jQuery对象本身
jQuery.extend({
    login:function(){
        return "Login OK"
    },
    uncheck: function() {
        return this.each(function() { this.checked = false; });
    }
});

//扩展jQuery对象(通常用来制作插件)
$.fn.extend({
    exit:function(){
        return "Exit OK"
    }
});


<!--  JQExtend2  -->
/**
 * Created by hb on 2016/5/10.
 */

//建议使用自执行函数

/*
()()
(function(arg){})(xincan)

*/

(function(jq){
    jq.extend({
        login:function(){
            return "Login OK"
        },
        uncheck: function() {
            return this.each(function() { this.checked = false; });
        }
    });

    jq.fn.extend({
        exit:function(){
            return "Exit OK"
        }
    });
})(jQuery);

//    jQuery.extend()     <==>  $.extend
//扩展jQuery对象本身

表单验证

http://files.cnblogs.com/files/wupeiqi/%E7%99%BB%E9%99%86%E6%B3%A8%E5%86%8C.zip

四、AJAX

  AJAX: Asynchronous Javascript And XML”(异步JavaScript和XML),AJAX = 异步 JavaScript和XML(标准通用标记语言的子集),不是jQuery。

 ajax

http://files.cnblogs.com/files/wupeiqi/ajax_demo.zip

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX-1</title>
    <script src="js/jquery-2.2.3.js"></script>
</head>
<body>

    <input id="n1" type="text" name="pp">
    <input type="button" value="提交" onclick="SubmitDATA();">

    <form>
        <p><input type="text" name="user"></p>
        <p><input type="password" name="pwd"></p>
        <input type="submit" value="提交">
    </form>

<script>
    function SubmitDATA(){
        //获取值
        var inpVal = $("#n1").val();
        var inpName = $("#n1").attr("name");
        console.log(inpName);
        $.ajax({
            url:"http://127.0.0.1:8000/index/",
            data:{"kk":123, inpName:inpVal},
            type:"POST",        //请求类型
            success:function(arg){
                //当请求执行完成后,自动调用
                //arg, 服务器返回的数据
                console.log(arg);
            },
            error:function(){
                //当请求错误之后,自动调用
            },
        });
    }

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

Ajax跨域_获取节目列表:

http://www.jxntv.cn/data/jmd-jxtv2.html

内容:

list({data:[ { "week":"周日", "list":[ { "time":"0030", "name":"通宵剧场六集连播", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0530", "name":"《都市现场》60分钟精编版(重播)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }
...]}
...]});

这不是一个标准的jsonp接口,因为

http://www.jxntv.cn/data/jmd-jxtv2.html?callback=showTv  返回的内容还是跟上面一样,主要是调用的方法还是list,是静态的

正常动态jsonp接口应该返回为:

showTV({data:[ { "week":"周日", "list":[ { "time":"0030", "name":"通宵剧场六集连播", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0530", "name":"《都市现场》60分钟精编版(重播)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }
...]}
...]});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>获取节目列表</title>
</head>
<body>

<div>
    <input type="button" value="获取节目" onclick="TVShows()">
</div>

<div id="container"></div>

<script src="js/jquery-2.2.3.js"></script>
<script>

    /**
     * AJAX
    1 JavaScript, DOM 不是jQuery
        Asynchronous Javascript And XML”(异步JavaScript和XML)

        ajax跨域:
            客户端
                发送格式: jsonp
参数名: 从get请求中获取函数名的参数名,一般为callback 函数名: 客户端本地的回调函数名 服务端 通过中获取函数名的参数名(如callback),获得客户端期望调用的客户端本地的函数名 函数名("json数据"); //把这样的内容返回给客户端,这就是在调用函数执行 2 $.ajax({}) $.get <==> $.ajax({type:"GET"}) $.post <==> $.ajax({type:"POST"}) 3 本域: 请求,直接返回 跨域: 请求,指定函数名,jsonp 返回,函数名(数据) * @constructor
*/ function TVShows(){ $.ajax({ url: "http://www.jxntv.cn/data/jmd-jxtv2.html", data: {}, type: "GET", dataType: "jsonp", // 相当于 http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list jsonp: "callback", jsonpCallback: "list", // 为什么是这个,这主要是http://www.jxntv.cn/data/jmd-jxtv2.html是个静态的,每次都调用的list();方法 success: function(jsonData){ //arg = {data:xxx} console.log(arg); var jsonpArray = jsonData.data; $.each(jsonpArray,function(k, v){ //k 下标 //v 数组值 var week = v.week; var temp = "<h1>" + week + "</h1>"; $("#container").append(temp); var listArray = v.list; $.each(listArray, function(kk, vv){ var link = vv.link; var name = vv.name; var time = vv.time; var HH = time.substr(0,2); var MM = time.substr(2,4); var newTime = HH + ":" + MM var temp2 = "<a href='" + link + "'>" + name + "&nbsp时间:" + newTime + "</a><br>" $("#container").append(temp2); }); }); }, error:function(){ //请求错误之后,自动调用 } }); } </script> </body> </html>

jquery ajax POST

function test(){
   $.ajax({
            //提交数据的类型 POST GET
            type:"POST",
            //提交的网址
            url:"testLogin.aspx",
            //提交的数据
            data:{Name:"sanmao",Password:"sanmaoword"},
            //返回数据的格式
            datatype: "html",//"xml", "html", "script", "json", "jsonp", "text".
            //在请求之前调用的函数
            beforeSend:function(){$("#msg").html("logining");},
            //成功返回之后调用的函数             
            success:function(data){
           $("#msg").html(decodeURI(data));            
            }   ,
            //调用执行后调用的函数
            complete: function(XMLHttpRequest, textStatus){
               alert(XMLHttpRequest.responseText);
               alert(textStatus);
                //HideLoading();
            },
            //调用出错执行的函数
            error: function(){
                //请求出错处理
            }         
         });

  }
原文地址:https://www.cnblogs.com/linkenpark/p/5426537.html