jQuery Ajax

测试jQuery模板
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Ajax</title>
    <!-- 引用在线jQuery文件 -->
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>

</body>
</html>
load()方法
  • 静态页面
index页面:
<button>按钮</button>
<div id="xiu"></div>
text页面:
<p class="p">文章</p>
<p>内容</p>

点击按钮在index页面的div里面加载text页面

$('button').click(function(){
    $('#xiu').load('text.html')
})

对载入的HTML筛选

$('button').click(function(){
    $('#xiu').load('text.html .p') //只显示class为p的文章
})
  • 动态页面
index页面:
<button>按钮</button>
<div id="xiu"></div>

不传递data(默认get提交)

js文件

$("button").click(function(){
    $("#xiu").load("php/text.php?url=kang");
})

 text.php文件

if($_GET["url"]=="kang"){
    echo "成功";
}else {
    echo "失败";
}

传递data(post提交)

js文件

$("button").click(function(){
    $("#xiu").load("php/text.php",{
        url:'kang'
    })
})
php文件
if($_POST["url"]=="kang"){
    echo "成功";
}else {
    echo "失败";
}
在Ajax数据载入完毕后,就能执行回调函数,也就是第三个参数
回调函数有三个可选参数
$("button").click(function(){
    $("#xiu").load("php/text.php",{},function(resp,stat,xhr){
        alert(resp);//返回PHP数据
        $("#xiu").html(resp + "添加");//修改resp数据
        alert(stat);//成功返回:success,错误返回:error
        alert(xhr);//返回对象
    });
})

 xhr对象属性

$get()和$post()
.load()方法是局部方法,因为他需要包含元素的JQuery对象作为前缀,
$.get()和$.post()是去全局方法,无需指定某个参数
对用途而言,.load()适合做静态文件的异步获取,而对于需要传递参数到服务器页面的,$.get()和$.post()更加合适
$get()方法有四个参数,前面三个参数和.load()一样,多了一个第四个参数type,即服务器返回内容的格式(xml,html,script,json,jsonp,text)
<?php
    if($.GET['url']=='xx'){
      echo "url=xx打印"
    }
?>
  • 方式一:通过直接在URL问号紧跟传参(post()不支持方法一)
$("button").click(function(){
    $.get("text.php?url=xx&a=b",function(resp,stat,xhr){
      $("#xiu").html(resp)
    })
})
  • 方式二:通过第二个参数data,字符串形式的键值对传参,然后自动转换为URL问号紧跟传参
$("button").click(function(){
    $.get("text.php","url=xx",function(resp,stat,xhr){
      $("#xiu").html(resp)
    })
})
  • 方式三:通过第二个参数data,对象形式的键值对传参,然后自动转换为URL问号紧跟传参
$("button").click(function(){
    $.get("text.php",{
    url:xx
    },function(resp,stat,xhr){
    $("#xiu").html(resp)
    })
})
  • 第四个参数
第四个参数type是指定异步返回的类型,一般情况下type参数是智能判断,并不需要我们主动设置,如果主动设置,则会强行按照指定类型格式返回
$("button").click(function(){
    $.get("text.php","url=xx",function(resp,stat,xhr){
      $("#xiu").html(resp)
    },"html") //本身是超文本,如果强行按照xml或者json数据格式返回的话,那就无法获取数据
})

异步加载xml

<?xml version="1.0"?>
<root>
    <url>xx</url>
</root>
$("button").click(function(){
    $.get("text.xml",function(resp,stat,xhr){
    alert($(resp).find("root").find("url").text()) //输出xx
    },"xml") //如果强行设置html数据格式返回的话,会把源文件输出
})
  • 异步加载json
[
    {
    "url" : "xx"
    }
]
$("button").click(function(){
    $.get("text.json",function(resp,stat,xhr){
    alert(resp[0].url) //输出xx
    },"json") //如果强行设置html数据格式返回的话,会把源文件输出
})
  • $.post()和$.get()的区别
GET请求是通过URL提交的,而POST请求则是HTTP信息实体提交
GET提交有大小限制(2KB),而POST方式不受限制
GET方式会被缓存下来,可能有安全问题,而POST不会缓存
GET方式通过$_GET[]获取,POST方式通过$_POST[]获取
$.getScript()和$.getJSON()
$.getScript()用于加载js文件
$("button").click(function(){
    $.getScript("text.js")
})
$.getJSON()用于加载json文件
$("button").click(function(){
    $.getJSON("text.json",function(resp,stat,xhr){
    alert(resp[0].url)
    })
})
$.ajax()
$.ajax()是所有Ajax方法中最底层的方法,所有的其他方法都是基于$.ajax()方法的封装,这个方法只有一个参数
  • 最基本的底层Ajax提交
$("button").click(function(){
    $.ajax({
        type : "POST", //默认GET提交
        url : "text.php", //提交的地址
        data : {
            url : xx
        },
        success : function(response,status,xhr){
             $(".xiu").html(response)
        }
    })
})
  • 最基本的表单提交
HTML页面:
<form>
    <input type="text" name="user"/>
    <input type="text" name="pass"/>
    <input type="radio" name="sex" value="男"/><input type="button" value="提交"/>
</form>
PHP页面:
<?php
    echo $_POST["user"]."*".$_POST["pass"]
?>
JavaScript页面:
$("input[type=button]").click(function(){
    type : "POST",
    url : "text.php",
    data : {
    user : $("input[name=user]").val(),
    pass : $("input[name=pass]").val()
    }
    //data : $("form").serialize(), //表单序列化,可以不用写上面的data对象
    success : function(resp,stat,xhr){
    $(".xiu").html(resp);
    }
})
  • .serialize()方法不但可以序列化表单的元素,还可以直接获取单选框,复选框和下拉框等内容
$("input[name=sex]").click(function(){
    $(".xiu").html($(this).serialize());
    //serialize()方法进行传输的时候进行了编码,所以需要decodeURIComponent()进行解码才能正常显示
    $(".xiu").html(decodeURIComponent($(this).serialize()))
})
  • .serializeArray()这个方法可以直接把数据整合成键值对的JSON对象
$("input[name=sex]").click(function(){
    console.log($(this).serializeArray()); //console.log()可以打印任何数据类型
    var json = $(this).serializeArray();
    $(".xiu").html(json[0].value); //页面上打印输出
})
  • 初始化重复的属性
$.ajaxSetup({
    type : "POST",
    url : "text.php",
    date : $("form").serialize()
})
$("input[type=button]").click(function(){
    success : function(resp,stat,xhr){
    $(".xiu").html(resp);
    }
})
  • 响应前后加载
$(document).ajaxStart(function(){
    alert("Ajax加载前执行");
}).ajaxStop(function(){
    alert("Ajax加载后执行");
})
  • 全局执行的顺序
$(document).ajaxSend(function(){
    alert("发送请求前执行");
}).ajaxComplete(function(){
    alert("请求完成后执行,不管对错最后执行");
}).ajaxSuccess(function(){
    alert("请求成功后执行");
}).ajaxError(funtion(){
    alert("请求失败后执行");
})
有时程序对于复杂的序列化解析能力有限,可以使用$.param()方法将对象转换为字符串键值对格式可以更加稳定准确的传递表单内容
$("input[type=button]").click(function(){
    type : "POST",
    url : "text.php",
    data : $param({
    user : $("input[name=user]").val(),
    pass : $("input[name=pass]").val()
    }),
    success : function(resp,stat,xhr){
    $(".xiu").html(resp);
    },
    error : function(xhr,errorText,errorType){
    alert("自定义错误")
    alert(errorText+"*"+errorType)
    alert(xhr.status+"*"+xhr.statusText)
    },
    timeout : 1000, //设置响应时间后停止
    global : false, //取消全局事件
})
  • JSON和JSONP
在同域的情况下,$.ajax()方法只要设置dataType属性即可加载JSON文件
<?php
    $xiu = array('a'=>1,'b'=>2,'c'=>3)
    $kang = json_encode($xiu) //将数组转换为json格式
    echo $kang
?>
$.ajax({
    url : "text.php",
    dataType : "json",
    success : function(ersponse,status,xhr){
    alert(ersponse.a); //输出1
    }
})
在非同域的情况下,可以使用JSONP(非官方的协议)
它允许服务器端集成返回至客户端
通过JavaScript callback的形式实现跨越访问(这仅仅是JSONP简单的实现形式)
<?php
    $xiu = array('a'=>1,'b'=>2,'c'=>3)
    $kang = json_encode($xiu) //将数组转换为json格式
    $anni = $_POST("callback")
    echo $anni."($kang)"
?>
  • $_getJSON()方法跨域获取JSON
$_getJSON("http://www.xiu.com/text.php?callback=?",function(response,status,xhr){
  $(".xiu").html(response.a)  
})
  • 使用$_ajax()方法跨域获取JSON的两种方式
$.ajax({
    url : "http://www.xiu.com/text.php?callback=?",
    dataType : "json",
    success : function(response,status,xhr){
    $(".xiu").html(response.a)
    }
})
$.ajax({
    url : "http://www.xiu.com/text.php",
    dataType : "jsonp",
    success : function(response,status,xhr){
    $(".xiu").html(response.a)
    }
})
jqXHR对象
  • 获取jqXHR对象
var jqXHR = $.ajax({})
 如果使用jqXHR对象的话,建议用.dome(),.always()和.fail()代替.success(),.complete()和.error()
 列如成功后回调函数
jqXHR.dome(function(response,status,xhr){
    $(".xiu").html(response)
})
使用jqXHR的连缀方式比$.ajax()的属性方式有三大优点
1.可连缀操作,可读性大大提高
jqXHR.dome().dome() //同时执行多个成功后的回调函数
2.可以多次执行同一个回调函数
3.为多个操作指定回调函数
var jqXHR = $.ajax("text.php")
var jqXHR2 = $.ajax("text2.php")
$.when(jqXHR,jqXHR).done(function(x,y){
    alert(x[0])
    alert(y[0])
})
 
 
 

猜你喜欢

转载自www.cnblogs.com/xiukang/p/8964313.html