jQuery-Ajax快捷方法

简介

  • AJAX 是与服务器交换数据的技术,它在不重载全部页面的情况下,实现了对部分网页的更新。
  • Query 提供多个与 AJAX 有关的方法。
  • 通过 jQuery AJAX 方法,您能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON 同时您能够把这些外部数据直接载入网页的被选元素中。

快捷方法(这些方法帮你用最少的代码发送常见的Ajax请求。)

一、load()

概述

  • 载入远程 HTML 文件代码并插入至 DOM 中。

  • 默认使用 GET 方式 - 传递附加参数时自动转换为 POST 方式。jQuery 1.2 中,可以指定选择符,来筛选载入的 HTML 文档,DOM 中将仅插入筛选出的 HTML 代码。语法形如 “url #some > selector”。请查看示例。

load(url, [data], [callback])

  • url:类型: String。必需的URL参数规定您希望加载的URL
  • data:类型: PlainObject, String。可选的,向服务器发送请求的Key/value参数,例如{name:”“,age:23}
  • callback(responseText, textStatus, XMLHttpRequest):类型: Function()。当请求成功后执行的回调函数。
    • responseTxt -包含调用成功时的结果内容
    • textStatus-包含调用的状态:可能是”success”、”notmodifiend”、”error”、”timeout”、”abort” 或”parsererror” 中的一个,最长见的是:success成功;error错误
    • XMLHttpRequest-经过jQuery封装的一XMLHttpRequest对象(保留其本身的所有属性和方法)

有一个PHP文件test.php

<?php
echo "hi 好久不见"
?>

获取php文件内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax()-load()</title>
    <script src="http://www.jq22.com/jquery/jquery-1.7.1.js"></script>
</head>

<body>
    <h5>ajax返回的数据:</h5>
    <p></p>
</body>
<script>
    //返回的内容放入p中
    $("p").load("test.php?"+Math.random(),function(response,status,xhr){
    //    console.log(response);//打印返回的内容
    //    console.log(status);//打印调用的状态
    //    console.log(xhr);//打印XMLHttpRequest对象
        if(status=="error"){
            alert("请求失败"+status+xhr.statusText)
        }

    })
</script>
</html>

二、jQuery.get()和jQuery.post()

两种在客户端和服务器端进行请求–响应常用方法是:GET 和 POST。

GET基本上用于从服务器获得(取回)数据。注释:GET方法可能返回缓存数据。

POST也可用于从服务器获取数据。不过,POST方法不会缓存数据,并且常用于连同请求一起发送数据。

(1)jQuery.get()

概述:

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

这是一个简单的 GET 请求功能以取代复杂 . a j a x 使 .ajax。

扫描二维码关注公众号,回复: 3994215 查看本文章

jQuery 1.12 中 jQuery.post 和 jQuery.get 支持对象参数,这样一来好处还比较多,比如设置回调函数的context,或者跨域 post 时可以withCredential: true。

jQuery.get(url, [data], [callback], [type])

  • url:待载入页面的URL地址
  • data:待发送 Key/value 参数。
  • callback:载入成功时回调函数。
  • type:返回内容格式,xml, html, script, json, text, _default。

这是一个Ajax功能的缩写,这相当于:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

success 回调函数会传入返回的数据,是根据MIME类型的响应,它可能返回的数据类型包括XML根节点, 字符串, JavaScript 文件, 或者 JSON 对象。 同时还会传入描述响应状态的字符串。
实例(取php中的内容):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax()_get()</title>
    <script src="http://www.jq22.com/jquery/jquery-1.7.1.js"></script>
</head>
<body>
    <h5>ajax返回的数据:</h5>
    <p>     </p>
</body>
<script>
    $.get("test.php?"+Math.random(),function(date,status,shr){
        $("p").append(date+"<br/>");
        $("p").append(status+"<br/>");
        $("p").append(shr.readyState);
    })
</script>
</html>

(2)jQuery.post()

概述:

  • 通过远程 HTTP POST 请求载入信息。
  • 这是一个简单的 POST 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax
    jQuery 1.12 中 jQuery.postjQuery.get 支持对象参数,这样一来好处还比较多,比如设置回调函数的context,或者跨域 post 时可以withCredential: true。

jQuery.post(url, [data], [callback], [type])

  • url:发送请求地址。
  • data:待发送 Key/value 参数。
  • callback:发送成功时回调函数。
  • type:返回内容格式,xml, html, script, json, text, _default。

示例:获得 test.php 页面返回的 json 格式的内容:

$.post("test.php", { "func": "getNameAndTime" },
          function(data){
          alert(data.name); // John
          console.log(data.time); //  2pm
          }, "json");

三、jQuery.getScript()和jQuery.getJSON()方法

$.getScript()和$.getJSON()方法专门用来加载JS/JSON文件

(1)jQuery.getScript()

概述

  • 通过 HTTP GET 请求载入并执行一个 JavaScript 文件。
  • jQuery 1.2 版本之前,getScript 只能调用同域 JS 文件。 1.2中,您可以跨域调用 JavaScript 文件。注意:Safari 2 或更早的版本不能在全局作用域中同步执行脚本。如果通过 getScript 加入脚本,请加入延时函数。

jQuery.getScript(url, [callback])

  • url:待载入 JS 文件地址。
  • callback:成功载入后回调函数。
    示例:动态加载新的官方jQuery 颜色动画插件,一旦该插件加载完成就会触发一些颜色动画。
<!DOCTYPE html>
<html>
<head>
  <style>
.block {
   background-color: blue;
   width: 150px;
   height: 70px;
   margin: 10px;
}</style>
  <script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<button id="go">&raquo; Run</button>

<div class="block"></div>

<script>
(function() {
  var url = "https://raw.github.com/jquery/jquery-color/master/jquery.color.js";
  $.getScript(url, function() {
    $("#go").click(function(){
      $(".block")
        .animate( { backgroundColor: "rgb(255, 180, 180)" }, 1000 )
        .delay(500)
        .animate( { backgroundColor: "olive" }, 1000 )
        .delay(500)
        .animate( { backgroundColor: "#00f" }, 1000 );
    });
  });
})();
</script>

</body>
</html>

示例: 加载js文件后改变宽
test.js文件

$(".block").width(50);
<script>
    $("#go").click(function(){
         $.getScript("text.js");
    })
</script>

(2)jQuery.getJSON( )

概述

  • 通过 HTTP GET 请求载入 JSON 数据。

  • 在 jQuery 1.2 中,您可以通过使用JSONP形式的回调函数来加载其他网域的JSON数据,如 “myurl?callback=?”。jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。 注意:此行以后的代码将在这个回调函数执行前执行。

jQuery.getJSON(url, [data], [callback])

  • url:发送请求地址。
  • data:待发送 Key/value 参数。
  • callback:载入成功时回调函数。

重要提示: 从jQuery 1.4开始,如果JSON文件包含一个语法错误,该请求通常会静静的失败。因此应该避免频繁手工编辑JSON数据。JSON语法规则比JavaScript对象字面量表示法更加严格。例如,所有在JSON中的字符串,无论是属性或值,必须用双引号括起来,更多JSON细节信息请参阅http://json.org/
示例:从 Flickr JSONP API中加载最近的四张标签为猫的图片:

<!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">

</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i == 3 ) return false;
    });
  });</script>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_42952665/article/details/82699136