jQuery.get()

jQuery.get( url, [ data ], [ success(data, textStatus, jqXHR) ], [ dataType ] ) 返回: jqXHR

描述: 通过服务器HTTP GET请求加载数据。

  • version added: 1.0jQuery.get( url, [ data ], [ success(data, textStatus, jqXHR) ], [ dataType ] )

    url一个包含发送请求的URL字符串

    data向服务器发送请求的Key/value参数

    success(data, textStatus, jqXHR)当请求成功后执行的回调函数。

    dataType从服务器返回的预期的数据类型。默认:智能猜测(xml, json, script, or html)。

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

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

成功的回调函数是根据MIME类型的响应,通过返回的数据包括XML根节点, 字符串, JavaScript 文件, 或者 JSON 对象。 它也是通过文本地位的反应。

在jQuery 1.5success回调函数还通过了“jqXHR”对象 jQuery 1.4中 ,它是通过XMLHttpRequest对象)。然而,由于JSONP形式和跨域的GET请求不使用的XHR,,在这些情况下, (j)XHRtextStatus回调参数传递的成功是不确定的。

大多数实现将指定一个成功的处理程序:

$.get('ajax/test.html', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});

这个例子所请求的全部HTML代码片段插在页面。

jqXHR 对象

在jQuery 1.5,所有jQuery的Ajax方法都返回的超集XMLHTTPRequest对象。这个jQuery XHR对象,或“jqXHR,”通过$.get()约定的接口实现返回,给它的所有属性,方法和约定的行为(见Deferred object获取更多信息)。为了方便和一致性,回调名称使用$.ajax(),它提供.error() .success().complete()方法。这些方法当$.ajax()请求终止时需要一个函数参数调用,这个函数接收$.ajax()回调函数名相同的参数。

在jQuery 1.5的约定接口也使jQuery的Ajax方法,其中包括$.get() ,以链多个.success().complete().error()回调的一个请求,甚至回调后分配这些请求可能已经完成。如果请求已经完成,立即触发回调。

// Assign handlers immediately after making the request,
  // and remember the jqxhr object for this request
  var jqxhr = $.get("example.php", function() {
    alert("success");
  })
  .success(function() { alert("second success"); })
  .error(function() { alert("error"); })
  .complete(function() { alert("complete"); });

  // perform other work here ...

  // Set another completion function for the request above
  jqxhr.complete(function(){ alert("second complete"); });

其他注意事项:

  • 由于浏览器的安全限制,大多数“Ajax”的要求,均采用同一起源的政策 ;该请求不能成功地检索来自不同的域,子域或协议的数据。
  • 如果一个jQuery.get()请求返回一个错误代码,它会静静的失败,除非脚本调用全局的.ajaxError()方法。在jQuery 1.5, 通过jQuery.get()返回的.error()方法的jqXHR对象也可用于处理错误。
  • Script和JSONP形式请求不受同源策略的限制。

Examples:

Example: 请求 test.php 页面, 但是忽略返回结果.

$.get("test.php");

Example: 请求 test.php 页面 并且发送url参数(虽然仍然忽视返回的结果)。

$.get("test.php", { name: "John", time: "2pm" } );

Example: 传递数组形式data参数给服务器 (虽然仍然忽视返回的结果).

$.get("test.php", { 'choices[]': ["Jon", "Susan"]} );

Example: Alert 从 test.php请求的数据结果 (HTML 或者 XML,取决于返回的结果).

$.get("test.php", function(data){
alert("Data Loaded: " + data);
});

Example: Alert 从 test.cgi请求并且发送url参数的数据结果 (HTML 或者 XML,取决于返回的结果).

$.get("test.cgi", { name: "John", time: "2pm" },
   function(data){
     alert("Data Loaded: " + data);
   });

Example: 获取test.php的页面已返回的JSON格式的内容 (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>).

$.get("test.php", { "func": "getNameAndTime" },
   function(data){
     alert(data.name); // John
     console.log(data.time); //  2pm
   }, "json");
jQuery 1.6 API 中文版Clove整理、修订