jquery学习(六)ajax

1.什么是ajax

简短地说,在不重载整个网页的情况下,AJAX 通过后台加载数据,并在网页上进行显示,也就是异步加载。

2.load方法

load() 方法从服务器加载数据,并把返回的数据放入被选元素中。
语法:

$(selector).load(URL,data,callback);
url:必需参数,请求的url
data:可选参数,发送至服务器的 key/value 数据。
callback:可选参数,请求完成时(不需要是success的)的回调函数。

例如:
可以将h3中的内容换成test文件中的内容

$("h3").load("../../doc/test");

也可以将test文件中的p元素加载到h3中

$("h3").load("../../doc/test p");

回调函数可以设置不同的参数:

responseTxt - 包含调用成功时的结果内容
statusTXT - 包含调用的状态

3.get方法

通过远程 HTTP GET 请求载入信息。

语法:

$(selector).get(url,data,success(response,status,xhr),dataType)

success:可选。规定当请求成功时运行的函数。
额外的参数:

  • response - 包含来自请求的结果数据
  • status - 包含请求的状态
  • xhr - 包含 XMLHttpRequest 对象

dataType:可选,规定预计的服务器响应的数据类型。
默认地,jQuery 将智能判断。
可能的类型:”xml”,”html”,”text”,”script”,”json”,”jsonp”

4.post方法

通过 HTTP POST 请求从服务器载入数据
语法:

jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)

5.getScript方法

通过 HTTP GET 请求载入并执行 JavaScript 文件。

语法:

jQuery.getScript(url,success(response,status))

6.ajax方法

通过 HTTP 请求加载远程数据。
语法:

jQuery.ajax([settings])

settings:可选。用于配置 Ajax 请求的键值对集合。可以通过 $.ajaxSetup() 设置任何选项的默认值。

常见的请求参数:

url:请求的url。
data:发送到服务器的数据。
type:请求方式。
dataType:预期服务器返回的数据类型。
success:请求成功后的回调函数。
error:请求失败时调用此函数。
complete:请求完成后回调函数 (请求成功或失败之后均调用)。
beforeSend:发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。
cache:类型为Boolean,默认为true,dataType为 script 和 jsonp 时默认为false,设置为false将不缓存此页面。

实例:

$.ajax({
    // the URL for the request
    url: "post.php",

    // the data to send (will be converted to a query string)
    data: {
        id: 123
    },

    // whether this is a POST or GET request
    type: "GET",

    // the type of data we expect back
    dataType : "json",

    // code to run if the request succeeds;
    // the response is passed to the function
    success: function( json ) {
        $( "<h1/>" ).text( json.title ).appendTo( "body" );
        $( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
    },

    // code to run if the request fails; the raw request and
    // status codes are passed to the function
    error: function( xhr, status, errorThrown ) {
        alert( "Sorry, there was a problem!" );
        console.log( "Error: " + errorThrown );
        console.log( "Status: " + status );
        console.dir( xhr );
    },

    // code to run regardless of success or failure
    complete: function( xhr, status ) {
        alert( "The request is complete!" );
    },

    beforeSend: function() {
    },
    cache: true //false
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值