您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页10 Talk to the server with Ajax

10 Talk to the server with Ajax

来源:二三娱乐

This chapter covers

  • A brief overview of Ajax
  • Loading preformatted HTML from the server
  • Making GET and POST requests
  • Exerting fine-grained control over requests
  • Setting default Ajax properties
  • Handling Ajax events

10.1 Brushing up on Ajax

10.1.1 Creating an XHR instance


var xhr;
if (window.ActiveXObject) {
  xhr = new ActiveXObject ('Microsoft.XMLHTTP');
} else if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
} else {
  throw new Error('Ajax is not supported by this browser')
}

XMLHttpRequest (XHR) methods and properties

Method Description
abort()
getAllResponseHeaders()
getResponseHeader(name)
open(method, url[, async[, username[, password]]])
overrideMimeType(mime)
send([content])
setRequestHeader(name, value)
onreadystatechange
readyState
response
responseText
responseType
responseXML
status
statusText
timeout
ontimeout
upload
withCredentials

10.1.2 Initiating the request


  1. Specify the HTTP method (such as POST or GET).
  2. Provide the URL of the server-side resource to be contacted.
  3. Let the XHR instance konw how it can inform you of its progress.
  4. Provide any body content for requests such as POST.
xhr.open('GET', '/some/resource/url');
xhr.send('a=1&b=2&c=3');

10.1.3 Keeping track of progress


xhr.onreadystatechange = function() {
  if (this.readyState === 4) {
    if (this.status >= 200 && this.status < 300) {
      // Success
    } else {
      // Problem
    }
  }
}

10.1.4 Getting the response


  • Instanitiating an XHR object requires browser-specific code.
  • Ready handlers need to sift through a lot of uninteresting state changes.
  • The response body needs to be dealt with in numerous ways, depending on its format.

10.2 Loading content into elements


var xhr;
if (window.ActiveXObject) {
 xhr = new ActiveXObject('Microsoft.XMLHTTP');
} else if (window.XMLHttpRequest) {
 xhr = new XMLHttpRequest();
} else {
 throw new Error('Ajax is not supported by this browser');
}
xhr.onreadystatechange = function() {
 if (this.readyState === 4) {
 if (this.status >= 200 && this.status < 300) {
 document.getElementById('elem').innerHTML = this.responseText;
 }
 }
}
xhr.open('GET', 'some-resource');
xhr.send();

10.2.1 Loading content with jQuery


load(url[, data][, callback])
Parameters
url (String)
data (String|Object|Array)
callback (Function)
Returns
The jQuery collection.

var updates = 1;
function pollInfo() {
  $('#container').load('/check-updates', function(responseText, textStatus, jqXHR) {
    if(textStatus === 'success') {
      $('#status-update').text('Data updated. Update #' + updates);
       updates++;
    }
    setTimeout(pollInfo, 1000);
  });
}
pollInfo();

serialize()
Parameters
none
Returns
The formatted query string.


serializeArray()
Parameters
none
Returns
The array of form data.


10.2.2 Loading dynamic HTML fragments


$('#boot-chooser-control').change(function(event) {
 $('#product-detail-pane').load(
 'actions/fetch-product-details.php',
 {
 model: $(event.target).val()
 },
 function() {
 $('[value=""]', event.target).remove();
 }
 );
});
$('#boot-chooser-control')
 .load('actions/fetch-boot-style-options.php')
 .change(function(event) {
 $('#product-detail-pane').load(
 'actions/fetch-product-details.php',
 {
 model: $(event.target).val()
 },
 function() {
 $('[value=""]', event.target).remove();
 }
 );
 });

10.3 Making GET and POST requests

10.3.1 Getting data with GET


$.get(url[, data][, callback][, dataType])
Parameters
url (String)
data (String|Object)
callback (Function)
dataType (String)
Returns
The jqXHR instance.

$('#boot-chooser-control')
 .change(function(event) {
 $.get(
 'actions/fetch-product-details.php',
 {
 model: $(event.target).val()
 },
 function(response) {
 $('#product-detail-pane').html(response);
 $('[value=""]', event.target).remove();
 }
 );
 });

10.3.2 Getting JSON data


$.getJSON(url [, data][, callback])
Returns
The jqXHR instance


10.3.3 Dynamically loading script


$.getScript(url[, callback])
Returns
The jqXHR instance.

getScript: function(url, callback) {
  return jQuery.get(url, undefined, callback, "script");
}
$('#load-button').click(function() {
 $.getScript('external.js');
 });
 $('#inspect-button').click(function() {
 someFunction(someVariable);
 });

10.3.4 Making POST requests


$.post(url[, data][, callback][, dataType])
Returns
The jqXHR instance


10.3.5 Implementing cascading dropdowns


$bootChooser.change(function() {
 $('#product-detail-pane').load(
 'actions/fetch-product-details.php',
 $(this).serialize()
 );
 // More to follow
});
$bootChooser.change(function() {
 $('#product-detail-pane').load(
 'actions/fetch-product-details.php',
 $(this).serialize()
 );
 // More to follow
});
$colorChooser.change(function() {
 $sizeChooser.load(
 'actions/fetch-size-options.php',
 $colorChooser
 .add($bootChooser)
 .serialize(),
 function() {
 $(this).prop('disabled', false);
 }
 );
});

10.4 Taking full control of an Ajax request

10.4.1 Making Ajax requests with all the trimmings


$.ajax(url[, options])
$.ajax([options])
Parameters
url (String)
options (Object)
Returns
The jqXHR instance.

Options for the $.ajax() utility function

Name Description
url
method
data
dataType
cache
context
timeout
global
contentType
success
error
complete
beforeSend
async
processData
contents
converters
crossDomain
headers
dataFilter
ifModified
isLocal
jsonp
jsonpCallback
username
password
scriptCharset
statusCode
xhr
xhrFields
accepts
mimeType
traditional

10.4.2 Setting request defaults


$.ajaxSetup(options)
Parameters
options (Object)
Returns
undefined

$.ajaxSetup({
  type: 'POST',
  timeout: 5000,
  dataType: 'html'
});

10.4.3 Handling Ajax events


jQuery Ajax event types

Event name Type Description
ajaxStart Global
beforeSend Local
ajaxSend Global
success Local
ajaxSuccess Global
error Local
ajaxError Global
complete Local
ajaxComplete Global
ajaxStop Global

ajaxComplete(callback)
ajaxError(callback)
ajaxSend(callback)
ajaxStart(callback)
ajaxStop(callback)
ajaxSuccess(callback)
Parameters
callback (Function)
Returns
The jQuery collection.

var $log = $('#log');
$(document).on(
 'ajaxStart ajaxStop ajaxSend ajaxSuccess ajaxError ajaxComplete',
 function(event) {
 $log.text($log.text() + event.type + '\n');
 }
);

10.4.4 Advanced Ajax utility functions


$.ajaxPrefilter([dataTypes,] callback)
Parameters
dataTypes (String)
callback (Function)
Returns
undefined

$.ajaxPrefilter('xml', function(options, originalOptions, jqXHR) {
 if ($.inArray(options.url, originalOptions.deniedDomains) !== -1) {
 console.log('Ajax request to ' + options.url + ' aborted');
 jqXHR.abort();
 } else {
 console.log('Ajax request performed');
 }
});
$.ajax(
 
 {
 dataType: 'xml',
 deniedDomains: [
 
 
 ]
 }
);

$.ajaxTransport([dataType], callback)
Parameters
dataType (String)
callback (Function)
Returns
undefined


10.5 Summary

load()
$.get()
$.getJSON()
$.post()
$.ajax()
$.ajaxSetup()
ajaxStart()
ajaxSend()
ajaxSuccess()
ajaxError()
ajaxComplete()
ajaxStop()

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务