AJAX---jQuery 中的ajax方法的基本使用

jQuery 中的 AJAX

jQuery 中有一套专门针对 AJAX 的封装,功能十分完善,经常使用,需要着重注意

参考:
http://www.jquery123.com/category/ajax/
http://www.w3school.com.cn/jquery/jquery_ref_ajax.asp

$.ajax

常用选项参数介绍:

url:请求地址

type:请求方法,默认为

get dataType:服务端响应数据类型

contentType:请求体内容类型,默认 application/x-www-form-urlencoded

data:需要传递到服务端的数据,如果 GET 则通过 URL 传递,如果 POST 则通过请求体传递

timeout:请求超时时间

beforeSend:请求发起之前触发

success:请求成功之后触发(响应状态码 200)

error:请求失败触发

complete:请求完成触发(不管成功与否)

    // 最基础的 调用
    $.ajax('./time.php', {
      type: 'post', // method 请求方法
      success: function (res) {
        // res => 拿到的只是响应体
        console.log(res)
      }
    })
    $.ajax({
      url: 'time.php',
      type: 'post',
      // 用于提交到服务端的参数,
      // 如果是 GET 请求就通过 url 传递
      // 如果是 POST 请求就通过请求体传递
      data: { id: 1, name: '张三' },
      success: function (res) {
        console.log(res)
      }
    })
    $.ajax({
      url: 'json.php',
      type: 'get',
      success: function (res) {
        // res 会自动根据服务端响应的 content-type 自动转换为对象
        // 这是 jquery 内部实现的
        console.log(res)
      }
    })
    $.ajax({
      url: 'json.php',
      type: 'get',
      // 设置的是请求参数
      data: { id: 1, name: '张三' },
      // 用于设置响应体的类型
      dataType: 'json',
      success: function (res) {
        // 一旦设置的 dataType 选项,就不再关心 服务端 响应的 Content-Type 了
        // 客户端会主观认为服务端返回的就是 JSON 格式的字符串
        console.log(res)
      }
    })

猜你喜欢

转载自www.cnblogs.com/jane-panyiyun/p/12283502.html
今日推荐