【jQuery】jQuery官方基本教程的学习笔记4-异步Ajax

摘要:

Ajax(Asynchornous JavaScript and XML)

主要API -----XMLHttpRequest

不同浏览器Ajax API不同 (jQuery帮助解决了)

不可跨域访问,但出现了一个技术CORS

一、Key Concepts 关键概念

1.GET和POST

最常用的两种提交到服务器方法(还要其他五种,delete。。。不记得了)

GET:地址栏可以看到传入到服务器参数值键值对。。。。。

POST:有些数据可以抓包看,通常不会缓存在浏览器。。。。。

2.Data Types 数据类型

1)text

传送简单的字符串

2)html

传输html代码块到页面

3)script

添加新的脚本JavaScript到页面

4)json

传输json格式的数据,可以包括数组,字符串,对象

5)jsonp

从另一个域传输json数据

6)xml

使用xml数据传输数据

3.A is for Asyncharonous ——A代表异步

Ajax默认异步处理,所以只能通过异步回调函数来处理响应

var response;
 
$.get( "foo.php", function( r ) {
    response = r;
});
 
console.log( response ); // undefined
$.get( "foo.php", function( response ) {
    console.log( response ); // server response
});

4.Same-Origin Policy and JSONP

一般情况下,Ajax请求只在同一协议,端口,域名下执行请求,jQuery可以解决

注意,IE10以下不支持跨域的AJax请求访问

使用JSONP可以通过js写甲苯实现跨域访问,避免上面的局限

5.Ajax and Firebug (webkit观察)

二、jQuery's Ajax-Related Methods关于jQuery的Ajax方法

所有方法的核心 $.ajax()

1.$.ajax()    详细介绍http://api.jquery.com/jQuery.ajax/

// Using the core $.ajax() method
$.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 (is done);
  // The response is passed to the function
  .done(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
  .fail(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;
  .always(function( xhr, status ) {
    alert( "The request is complete!" );
  });

在请求的时候,需要告诉请求的数据格式,防止出现响应错误,收不到正确的服务器数据格式,如:需要请求json数据格式,那么头部,需要写上 application/json

2.$.ajax()Options 选项

常用的有下面几个,详细的选项介绍:http://api.jquery.com/jQuery.ajax/

1)async

默认为true,如果想同步执行请求,设置false即可。但是,设置成false后,你的请求直到收到响应后才会去执行其他代码块

2)cache

缓存,是否设置,默认true,对所有的数据类型dataType有效

3)done

如果请求成功,将运行回调函数,该函数将接受响应的数据(json格式转换为js对象),同时,其他数据都是原类型

4)fail

如果出现错误,运行该回调函数

5)always

不管请求失败还是成功,该回调函数都会运行

6)context

回调函数运行的范围

7)data

将要发送到服务器的数据,可以是对象,也可以是查询字符串

8)dataType

期望从服务器返回的数据类型,如果没有明确指定的话,jQuery将根据响应的MIME来确定

9)jsonp

当执行JSONP请求的时候需要发送查询字符串的回到名称,默认就是”callback”

10)timeout

超时,单位毫秒,即等待多长服务器响应时间视为失败

11)traditional

设置为true则将使用jQu1.4参数序列化风格,详细见http://api.jquery.com/jQuery.param/

12)type

请求方式,"POST" 或者"GET",默认为“GET”,其他方式比如"DELETE"也可以,但是可能有些浏览器不支持而已

13)url

请求地址URL,是$.ajax()中必须要配置的选项,其他选项都是可选配置的

3.Convenience Methods 常用简便方法

只需要简单配置一些选项就可以完成异步请求

1)$.get

给提供的URL执行GET请求

2)$.post

给提供的URL执行POST请求

3)$.getScript

给页面添加js脚本

4)$.getJSON

执行GET提交请求,期望返回JSON格式,在不同情况下,该方法将会返回下面这些参数,依次是:

(1)url

请求的URL,必须的

(2)data

(3)success callback

(4)data type

// Using jQuery's Ajax convenience methods
 
// Get plain text or HTML
$.get( "/users.php", {
    userId: 1234
}, function( resp ) {
    console.log( resp ); // server response
});
 
// Add a script to the page, then run a function defined in it
$.getScript( "/static/js/myScript.js", function() {
    functionFromMyScript();
});
 
// Get JSON-formatted data from the server
$.getJSON( "/details.php", function( resp ) {
 
    // Log each key in the response data
    $.each( resp, function( key, value ) {
        console.log( key + " : " + value );
    });
});

4.$.fn.load

.load()方法是jQuery ajax所有方法中唯一一个供选择器调用的方法,去填充选择的元素里面的内容

// Using .load() to populate an element
$( "#newContent" ).load( "/foo.html" );
// Using .load() to populate an element based on a selector
$( "#newContent" ).load( "/foo.html #myDiv h1:first", function( html ) {
    alert( "Content updated!" );
});

三、Ajax and Forms

1.Serialization

1).serialize()

.serialize()方法序列化表单的数据为一个查询字符串,必须要有一个name属性,

// Turning form data into a query string
$( "#myForm" ).serialize();
 
// Creates a query string like this:
// field_1=something&field2=somethingElse

2).serializeArray()

发送一个数据对象,该方法更方便

// Creating an array of objects containing form data
$( "#myForm" ).serializeArray();
 
// Creates a structure like this:
// [
//   {
//     name : "field_1",
//     value : "something"
//   },
//   {
//     name : "field_2",
//     value : "somethingElse"
//   }
// ]

2.Client-side validate客户端验证

主要用在提交表单前验证,当然也可以在服务器端验证

// Using validation to check for the presence of an input
$( "#form" ).submit(function( event ) {
 
    // If .required's value's length is zero
    if ( $( ".required" ).val().length === 0 ) {
 
        // Usually show some kind of error message here
 
        // Prevent the form from submitting
        event.preventDefault();
    } else {
 
        // Run $.ajax() here
    }
});
// Validate a phone number field
$( "#form" ).submit(function( event ) {
    var inputtedPhoneNumber = $( "#phone" ).val();
 
    // Match only numbers
    var phoneNumberRegex = /^\d*$/;
 
    // If the phone number doesn't match the regex
    if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) {
 
        // Usually show some kind of error message here
 
        // Prevent the form from submitting
        event.preventDefault();
    } else {
 
        // Run $.ajax() here
    }
});

3.Prefiltering

在发送请求钱修改ajax选项

// Using a proxy with a prefilter
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    if ( options.crossDomain ) {
        options.url = "http://mydomain.net/proxy/" + encodeURIComponent( options.url );
        options.crossDomain = false;
    }
});
// Using the optional dataTypes argument
$.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
 
    // Do all of the prefiltering here, but only for
    // requests that indicate a dataType of "JSON" or "script"
});

四、Working with JSONP

// Using YQL and JSONP
$.ajax({
    url: "http://query.yahooapis.com/v1/public/yql",
 
    // The name of the callback parameter, as specified by the YQL service
    jsonp: "callback",
 
    // Tell jQuery we're expecting JSONP
    dataType: "jsonp",
 
    // Tell YQL what we want and that we want JSON
    data: {
        q: "select title,abstract,url from search.news where query=\"cat\"",
        format: "json"
    },
 
    // Work with the response
    success: function( response ) {
        console.log( response ); // server response
    }
});

五、Ajax Events Ajax事件

// Setting up a loading indicator using Ajax Events
$( "#loading_indicator" )
    .ajaxStart(function() {
        $( this ).show();
    })
    .ajaxStop(function() {
        $( this ).hide();
    });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿来小同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值