发布于 2015-08-12 16:03:23 | 12132 次阅读 | 评论: 1 | 来源: 网络整理

Ajax请求

目录:

 

$.ajax

$.ajax(options) ⇒ XMLHttpRequest 

执行Ajax请求。请求地址可以是本地的或者跨域的,在支持的浏览器中通过 HTTP access control或者通过 JSONP来完成。

参数:

  • type (默认: “GET”):请求方法 (“GET”, “POST”, or other)
  • url (默认: 当前地址):发送请求的地址
  • data (默认:none):发送到服务器的数据;如果是get请求,它会自动被作为参数拼接到url上。非String对象将通过 $.param 得到序列化字符串。
  • processData (默认: true): 对于非Get请求。是否自动将 data 转换为字符串。
  • contentType (默认: “application/x-www-form-urlencoded”): 发送信息至服务器时内容编码类型。 (这也可以通过设置headers headers)。通过设置 false 跳过设置默认值。
  • dataType (默认: none):预期服务器返回的数据类型(“json”, “jsonp”, “xml”, “html”, or “text”)
  • timeout (默认: 0): 设置请求超时时间(毫秒),0表示不超时。
  • headers (默认:{}): 一个额外的"{键:值}"对映射到请求一起发送
  • async (默认: true):默认设置下,所有请求均为异步。如果需发送同步请求,请将此设置为 false
  • global (默认: true):请求将触发全局AJAX事件处理程序,设置为 false 将不会触发全局 AJAX 事件。
  • context (默认: window): 这个对象用于设置Ajax相关回调函数的上下文(this指向)。
  • traditional (默认:false):激活传统的方式通过$.param来得到序列化的 data

如果URL中含有 =?或者dataType是“jsonp”,这讲求将会通过注入一个 <script>标签来代替使用 XMLHttpRequest (查看 JSONP)。此时对 contentType, dataType, headers有限制,async 不被支持。

Ajax 回调函数

你可以指定以下的回调函数,给出的执行顺序:

  1. beforeSend(xhr, settings):请求发出前调用,它接收xhr对象和settings作为参数对象。如果它返回 false ,请求将被取消。

  2. success(data, status, xhr):请求成功之后调用。传入返回后的数据,以及包含成功代码的字符串。

  3. error(xhr, errorType, error):请求出错时调用。 (超时,解析错误,或者状态码不在HTTP 2xx)。

  4. complete(xhr, status):请求完成时调用,无论请求失败或成功。

Ajax 事件

global: true时。在Ajax请求生命周期内,以下这些事件将被触发。

  1. ajaxStart (global):如果没有其他Ajax请求当前活跃将会被触发。

  2. ajaxBeforeSend (data: xhr, options):再发送请求前,可以被取消。

  3. ajaxSend (data: xhr, options):像 ajaxBeforeSend,但不能取消。

  4. ajaxSuccess (data: xhr, options, data):当返回成功时。

  5. ajaxError (data: xhr, options, error):当有错误时。

  6. ajaxComplete (data: xhr, options):请求已经完成后,无论请求是成功或者失败。

  7. ajaxStop (global):如果这是最后一个活跃着的Ajax请求,将会被触发。

默认情况下,Ajax事件在document对象上触发。然而,如果请求的 context 是一个dom节点,该事件会在此节点上触发然后再dom中冒泡。唯一的例外是 ajaxStart & ajaxStop这两个全局事件。

$(document).on('ajaxBeforeSend', function(e, xhr, options){
        // This gets fired for every Ajax request performed on the page.
        // The xhr object and $.ajax() options are available for editing.
        // Return false to cancel this request.
        })

        $.ajax({
        type: 'GET',
        url: '/projects',
        // data to be added to query string:
        data: { name: 'Zepto.js' },
        // type of data we are expecting in return:
        dataType: 'json',
        timeout: 300,
        context: $('body'),
        success: function(data){
        // Supposing this JSON payload was received:
        //   {"project": {"id": 42, "html": "<div>..." }}
        // append the HTML to context object.
        this.append(data.project.html)
        },
        error: function(xhr, type){
        alert('Ajax error!')
        }
        })

        // post a JSON payload:
        $.ajax({
        type: 'POST',
        url: '/projects',
        // post payload:
        data: JSON.stringify({ name: 'Zepto.js' }),
        contentType: 'application/json'
        })
    
 

$.ajaxJSONP

Deprecated, use $.ajax instead.

$.ajaxJSONP(options) ⇒ mock XMLHttpRequest
  

执行JSONP跨域获取数据。

此方法相对 $.ajax 没有优势,建议不要使用。

 
 

$.ajaxSettings

一个包含Ajax请求的默认设置的对象。大部分的设置在 $.ajax中已经描述。以下设置为全局非常有用:

Object containing the default settings for Ajax requests. Most settings are described in $.ajax. The ones that are useful when set globally are:

  • timeout (默认: 0):对Ajax请求设置一个非零的值指定一个默认的超时时间,以毫秒为单位。
  • global (默认: true):设置为false。以防止触发Ajax事件。
  • xhr (默认:XMLHttpRequest factory):设置为一个函数,它返回XMLHttpRequest实例(或一个兼容的对象)
  • accepts: 从服务器请求的MIME类型,指定dataType值:
    • script: “text/javascript, application/javascript”
    • json: “application/json”
    • xml: “application/xml, text/xml”
    • html: “text/html”
    • text: “text/plain”
 

$.get

$.get(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest
      $.get(url, [data], [function(data, status, xhr){ ... }], [dataType]) ⇒ XMLHttpRequest [v1.0]
  

执行一个Ajax GET请求。这是一个 $.ajax的简写方式。

$.get('/whatevs.html', function(response){
        $(document.body).append(response)
        })
    
 

$.getJSON

$.getJSON(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest
      $.getJSON(url, [data], function(data, status, xhr){ ... }) ⇒ XMLHttpRequest [v1.0]
  

通过 Ajax GET请求获取JSON数据。这是一个 $.ajax 的简写方式。

$.getJSON('/awesome.json', function(data){
        console.log(data)
        })

        // fetch data from another domain with JSONP
        $.getJSON('//example.com/awesome.json?callback=?', function(remoteData){
        console.log(remoteData)
        })
    
 

$.param

$.param(object, [shallow]) ⇒ string
      $.param(array) ⇒ string
  

创建一个序列化的数组或对象,适用于一个URL 地址查询字符串或Ajax请求。如果shallow设置为true。嵌套对象不会被序列化,嵌套数组的值不会使用放括号在他们的key上。

此外,还接受 serializeArray格式的数组,其中每个项都有 “name” 和 “value”属性。

Also accepts an array in serializeArray format, where each item has “name” and “value” properties.

$.param({ foo: { one: 1, two: 2 }})
        //=> "foo[one]=1&foo[two]=2)"

        $.param({ ids: [1,2,3] })
        //=> "ids[]=1&ids[]=2&ids[]=3"

        $.param({ ids: [1,2,3] }, true)
        //=> "ids=1&ids=2&ids=3"

        $.param({ foo: 'bar', nested: { will: 'not be ignored' }})
        //=> "foo=bar&nested[will]=not+be+ignored"

        $.param({ foo: 'bar', nested: { will: 'be ignored' }}, true)
        //=> "foo=bar&nested=[object+Object]"
    
 

$.post

$.post(url, [data], function(data, status, xhr){ ... }, [dataType]) ⇒ XMLHttpRequest
  

执行Ajax POST请求。这是一个 $.ajax 的简写方式。

$.post('/create', { sample: 'payload' }, function(response){
        // process response
        })
    

data 参数可以是一个字符串:

$.post('/create', $('#some_form').serialize(), function(response){
        // ...
        })
    
 

load

load(url, function(data, status, xhr){ ... }) ⇒ self
  

通过GET Ajax载入远程 HTML 文件代码并插入至 DOM 中。另外,一个css选择器可以在url中指定,像这样,可以使用匹配selector选择器的HTML内容来更新集合。

Set the html contents of the current collection to the result of a GET Ajax call to the given URL. Optionally, a CSS selector can be specified in the URL, like so, to use only the HTML content matching the selector for updating the collection:

$('#some_element').load('/foo.html #bar')
    

当这种方法执行, 它将检索 foo.html 页面的内容,Zepto会获取ID为bar元素的内容,并且插入到ID为 some_element 元素,而其他的被检索到的元素将被废弃。

如果css选择器不存在。将使用完整的返回文本。

请注意,在没有选择器的情况下,任何javascript块都会执行。如果带上选择器,匹配选择器内的script将会被删除。

最新网友评论  共有(1)条评论 发布评论 返回顶部
ggg 发布于2017-02-06 16:41:26
gggg
支持(0)  反对(0)  回复

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务