Taogen's Blog

Stay hungry stay foolish.

jQuery Ajax Basic

Ajax Requests

jQuery.ajax(url [, settings ]) or jQuery.ajax( [settings] )

Perform an asynchronous HTTP (Ajax) request.

  • $.ajax()
  • $.get()
  • $.post()
  • $({selector}).load(): Load data from the server and place the returned HTML into the matched elements.

jQuery.ajaxSetup(options)

Set default values for future Ajax requests. Its use is not recommended.

options: A set of key/value pairs that configure the default Ajax request. All options are optional.

All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup().

Note: The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.

For example: Sets the defaults for Ajax requests to the url “/xmlhttp/“, disables global handlers and uses POST instead of GET. The following Ajax requests then sends some data without having to set anything else.

$.ajaxSetup({
url: "/xmlhttp/",
global: false,
type: "POST"
});
$.ajax({ data: myData });

Ajax Settings

settings

  • Type: PlainObject

A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup()

Settings for Request

accepts

  • Type: PlainObject
  • default: depends on dataType

A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept request header. This header tells the server what kind of response it will accept in return.

async

  • Type: Boolean
  • default: true

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

cache

  • Type: Boolean
  • Default: true, false for dataType 'script' and 'jsonp'

If set to false, it will force requested pages not to be cached by the browser.

Retrieve the latest version of an HTML page.

$.ajax({
url: "test.html",
cache: false
})
.done(function( html ) {
$( "#results" ).append( html );
});

contentType

  • Type: Boolean or String
  • Default: 'application/x-www-form-urlencoded; charset=UTF-8'

When sending data to the server, use this content type. Default is “application/x-www-form-urlencoded; charset=UTF-8”, which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

crossDomain

  • Type: Boolean
  • Default: false for same-domain requests, true for cross-domain requests

If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5)

data

  • Type: PlainObject or String or Array

Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL.

When data is an object, jQuery generates the data string from the object’s key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf". If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.

When data is passed as a string it should already be encoded using the correct encoding for contentType, which by default is application/x-www-form-urlencoded.

In requests with dataType: "json" or dataType: "jsonp", if the string contains a double question mark (??) anywhere in the URL or a single question mark (?) in the query string, it is replaced with a value generated by jQuery that is unique for each copy of the library on the page (e.g. jQuery21406515378922229067_1479880736745).

dataType

  • Type: String
  • Default: Intelligent Guess (xml, json, script, or html)
  • values: “xml”, “html”, “script”, “json”, “jsonp”, “text”

The type of data that you’re expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.

multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType.

headers

  • Type: PlainObject
  • default: {}

An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5)

ifModified

  • Type: Boolean
  • Default: false

Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the ‘etag’ specified by the server to catch unmodified data.

isLocal

  • Type: Boolean
  • Default: depends on current location protocol

Allow the current environment to be recognized as “local,” (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1)

jsonp

  • Type: String or Boolean

Override the callback function name in a JSONP request. This value will be used instead of ‘callback’ in the ‘callback=?’ part of the query string in the url. So {jsonp:’onJSONPLoad’} would result in ‘onJSONPLoad=?’ passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the “?callback” string to the URL or attempting to use “=?” for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: “callbackName” }. If you don’t trust the target of your Ajax requests, consider setting the jsonp property to false for security reasons.

jsonpCallback

  • Type: String or Function()

Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery.

method

  • Type: String
  • Default: 'GET'

mimeType

  • Type: String

A mime type to override the XHR mime type.

password

  • Type: String

A password to be used with XMLHttpRequest in response to an HTTP access authentication request.

processData

  • Type: Boolean
  • Default: true

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type “application/x-www-form-urlencoded”. If you want to send a DOMDocument, or other non-processed data, set this option to false.

scriptAttrs

  • Type: PlainObject

Defines an object with additional attributes to be used in a “script” or “jsonp” request. The key represents the name of the attribute and the value is the attribute’s value. If this object is provided it will force the use of a script-tag transport. For example, this can be used to set nonce, integrity, or crossorigin attributes to satisfy Content Security Policy requirements. (version added: 3.4.0)

scriptCharset

  • Type: String

Only applies when the “script” transport is used. Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. Alternatively, the charset attribute can be specified in scriptAttrs instead, which will also ensure the use of the “script” transport.

timeout

  • Type: Number

Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent.

traditional

  • Type: Boolean

Set this to true if you wish to use the traditional style of param serialization.

traditional=true, param is encoded, traditional=false, params is decoded

var myObject = {
a: {
one: 1,
two: 2,
three: 3
},
b: [ 1, 2, 3 ]
};
var recursiveEncoded = $.param( myObject );
var recursiveDecoded = decodeURIComponent( $.param( myObject ) );
a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3
a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3

type

  • Type: String
  • Default: ‘GET’

An alias for method. You should use type if you’re using versions of jQuery prior to 1.9.0.

url

  • Type: String
  • Default: The current page

A string containing the URL to which the request is sent.

username

  • Type: String

A username to be used with XMLHttpRequest in response to an HTTP access authentication request.

xhr

  • Type: Function()
  • default: ActiveXObject when available (IE), the XMLHttpRequest otherwise

Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.

xhrFields

  • Type: PlainObject

An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
});

Settings for Response

contents

  • Type: PlainObject

An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5)

context

  • Type: PlainObject

This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

converters

  • Type: PlainObject
  • Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}

An object containing dataType-to-dataType converters. Each converter’s value is a function that returns the transformed value of the response. (version added: 1.5)

Settings for Ajax Event

beforeSend

  • Type: Function( jqXHR jqXHR, PlainObject settings )

A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request.

complete

  • Type: Function( jqXHR jqXHR, String textStatus )

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

dataFilter

  • Type: Function( String data, String type ) => Anything

A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the ‘dataType’ parameter.

error

  • Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are “timeout”, “error”, “abort”, and “parsererror”. When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as “Not Found” or “Internal Server Error.” (in HTTP/2 it may instead be an empty string) As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.

statusCode

  • Type: PlainObject
  • Default: {}

An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});

success

  • Type: Function( Anything data, String textStatus, jqXHR jqXHR )

A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.

Settings for Global Ajax Event

global

  • Type: Boolean
  • default: true

Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered.

The jqXHR Object

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser’s native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

overrideMimeType()

As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:

$.ajax({
url: "https://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});

Promise interface

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

  • jqXHR.done(function( data, textStatus, jqXHR ) {});

    An alternative construct to the success callback option, refer to deferred.done() for implementation details.

  • jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

    An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

  • jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); (added in jQuery 1.6)

    An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

    In response to a successful request, the function’s arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

  • jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

    Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

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

// Perform other work here ...

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

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:

  • readyState
  • responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
  • status
  • statusText (may be an empty string in HTTP/2)
  • abort( [ statusText ] )
  • getAllResponseHeaders() as a string
  • getResponseHeader( name )
  • overrideMimeType( mimeType )
  • setRequestHeader( name, value ) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
  • statusCode( callbacksByStatusCode )

No onreadystatechange mechanism is provided, however, since done, fail, always, and statusCode cover all conceivable requirements.

Data Type

Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.

The available data types are text, html, xml, json, jsonp, and script.

If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.

If xml is specified, the response is parsed using jQuery.parseXML before being passed, as an XMLDocument, to the success handler. The XML document is made available through the responseXML property of the jqXHR object.

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

If script is specified, $.ajax() will execute the JavaScript that is received from the server before passing it on to the success handler as a string.

If jsonp is specified, $.ajax() will automatically append a query string parameter of (by default) callback=? to the URL. The jsonp and jsonpCallback properties of the settings passed to $.ajax() can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. $.ajax() will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the $.ajax() success handler.

Sending Data to the Server

By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.

Additional Notes

  • Due to browser security restrictions, most “Ajax” requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
  • Script and JSONP requests are not subject to the same origin policy restrictions.

Global Ajax Event Handlers

These methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery.ajaxSetup() is true, which it is by default. Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.

  • .ajaxStart(), Register a handler to be called when the first Ajax request begins. This is an Ajax Event.
  • .ajaxSend(), Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.
  • .ajaxStop(), Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.
  • .ajaxComplete(), Register a handler to be called when Ajax requests complete. This is an AjaxEvent.
  • .ajaxError(), Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.
  • .ajaxSuccess(), Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.

Helper Functions

These functions assist with common idioms encountered when performing Ajax tasks.

  • jQuery.param(), Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.
  • .serialize(), Encode a set of form elements as a string for submission.
  • .serializeArray(), Encode a set of form elements as an array of names and values.

Low-Level Interface

These methods can be used to make arbitrary Ajax requests.

jQuery.ajax()

Perform an asynchronous HTTP (Ajax) request.

jQuery.ajaxPrefilter()

Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().

jQuery.ajaxSetup()

Set default values for future Ajax requests. Its use is not recommended.

jQuery.ajaxTransport()

Creates an object that handles the actual transmission of Ajax data.

Shorthand Methods

These methods perform the more common types of Ajax requests in less code.

jQuery.get()

Load data from the server using a HTTP GET request.

jQuery.getJSON()

Load JSON-encoded data from the server using a GET HTTP request.

jQuery.getScript()

Load a JavaScript file from the server using a GET HTTP request, then execute it.

jQuery.post()

Send data to the server using a HTTP POST request.

.load()

Load data from the server and place the returned HTML into the matched elements.

Request Data Handling

Query String

// by processData
$.ajax({
url: url,
type: 'GET',
processData: true, // default: true
data: {JSON_object}
});

or

// by $.param(data)
$.ajax({
url: url + '?' + $.param(data),
type: 'xxx'
});

Request Body JSON

// data: JSON_string
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: {JSON_string}
});

or

// data: JSON_object, processData: false
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
processData: false, // default: true
data: {JSON_object}
});

FormData

Ajax request with application/x-www-form-urlencoded

// data: form.serialize(), processData: false
$.ajax({
url: url,
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
processData: false, // default: true
data: form.serialize()
});

or

// data: {JSON_object}, processData: true
$.ajax({
url: url,
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
processData: true, // default: true
data: {JSON_object}
});

Ajax request with multipart/form-data

// data: formdata, processData: false
$.ajax({
url: url,
type: 'POST',
contentType: 'multipart/form-data',
processData: false, // default: true
data: formdata
});

References

[1] jQuery API Documentation

Backend

Design

  • Class hierarchy design.

Global Functions

  • Core
    • For user
      • Authentication and authorization(menu, privilege, data scope). Sign in and sign out. Session Expiration Time. User, role, privilege. Data privilege and operation privilege.
      • File upload and download.
      • Scheduling Tasks.
    • For system
      • Exception handling. Error message encapsulation.
      • Logging. Method logging with AOP and annotations.
      • Cache handling.
      • Concurrency and asynchronization.
      • Testing. Unit testing.
      • HTTP clients
  • Others
    • For user
      • File online preview.
      • File conversion.
      • SSO (Single Sign on)
      • Web Socket and browser notification. Push messages to client browser pages. (implemented by WebSocket or Ajax loop call)
      • Workflow.
      • I18n (database value, Java string value, JSP element value)
      • Full-text Search by Elasticserach.
    • For system
      • Filter error request.
      • Enable CORS(Cross-Origin Resource Sharing) on server-side.
      • Prevent duplicate form submission.
      • Using multiple data sources.
      • Performance optimization. For example, MySQL optimization. Indexing, optimizing schema and SQL. JVM optimization.
      • Data import into and export from MySQL and Elasticsearch.
      • Third party API access.
      • HTTPS.
      • Reverse Proxy Server.
      • DevOps. Git Flow, code review, test, package, deployment.
      • Crawler and anti-cralwer.

Module Functions

  • RESTful API. CRUD API + UI pages (single table, left tree right table, one-to-many nested tables)

    • Request parameters to POJO. E.g. spring framework@ModelAttribute, @RequestBody.
    • Data validation. E.g. spring framework@Validated).
    • Type conversion. E.g. spring framework @DateTimeFormat for datetime, @JsonSerialize for enumeration).
    • Data formatting. E.g. spring framework @JsonFormat for datetime, @JsonValue form enumeration).
    • Service transaction.
    • Persistence. CRUD.
  • Table data import from and export to Excel file.

  • Aggregation query (SQL, ES) and UI charts.

  • Unit tests.

Frontend

Basic UI Components

  • Top bar <header>. (Logo, website name, user center link, login/logout)
  • Horizontal navigation bar <nav>.
  • Left vertical sidebar menu <aside>.
  • Breadcrumb.
  • Content area <main>, <section>, <article>. (Search, Table and pagination, Form)
  • Bottom footer <footer>.

Global Functions

  • Copy text.
  • View bigger picture.
  • Prevent duplicate form submission.
  • Redirect to another page.
  • Send CRUD HTTP requests. Submit form.
  • Initialize operation privilege.
  • Load components.
  • File structure. Separated index, edit, view page.
  • Alert success and error message.
  • Send CORS Ajax request with jQuery.
  • Send browser notifications.

Module Functions

  • List page
    • Initialize operation privilege.
    • Initialize index page. Display breadcrumb, load search area elements (input, select, date time picker), display operation buttons row, load table and pagination, additionally, may load left area tree.
    • Index page add, edit, delete, search, import/export buttons bind events.
    • Search. Send request with form serialize or FormData.
    • Delete rows.
  • Edit page
    • Initialize edit page title, form elements, and submit button. Form elements: input, radio, checkbox, select, select picker, file, rich text editor, date time picker, and input tags.
    • Add edit page bind events.
    • Form data validation. Show error messages.
    • Save or update. Submit form, send request with FormData or JSON.
  • Other page
    • Statistical charts.
    • Complex page layout and style.

References

Semantic Elements in HTML

Introduction

cron is a UNIX tool that has been around for a long time, so its scheduling capabilities are powerful and proven.

The software utility cron also known as cron job is a time-based job scheduler in Unix-like computer operating systems. Users that set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like downloading files from the Internet and downloading email at regular intervals. The origin of the name cron is from the Greek word for time, χρόνος (chronos).

Cron is most suitable for scheduling repetitive tasks. Scheduling one-time tasks can be accomplished using the associated at utility.

Format

A cron expression is a string comprised of 6 or 7 fields separated by white space.

second, minute, hour, day of month, month, day(s) of week

Fields can contain any of the allowed values, along with various combinations of the allowed special characters for that field. The fields are as follows:

Field Name Mandatory Allowed Values Allowed Special Characters
Seconds YES 0-59 , - * /
Minutes YES 0-59 , - * /
Hours YES 0-23 , - * /
Day of month YES 1-31 , - * ? / L W
Month YES 1-12 or JAN-DEC , - * /
Day of week YES 1-7 or SUN-SAT , - * ? / L #
Year NO empty, 1970-2099 , - * /

So cron expressions can be as simple as this: * * * * ? *

or more complex, like this: 0/5 14,18,3-39,52 * ? JAN,MAR,SEP MON-FRI 2002-2010

Special characters

  • * (“all values”) - used to select all values within a field. For example, “*****” in the minute field means “every minute”.
  • ? (“no specific value”) - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but don’t care what day of the week that happens to be, I would put “10” in the day-of-month field, and “?” in the day-of-week field.

Note: ‘?’ can only be specfied for Day-of-Month or Day-of-Week.

  • - - used to specify ranges. For example, “10-12” in the hour field means “the hours 10, 11 and 12”.
  • , - used to specify additional values. For example, “MON,WED,FRI” in the day-of-week field means “the days Monday, Wednesday, and Friday”.
  • / - used to specify increments. For example, “0/15” in the seconds field means “the seconds 0, 15, 30, and 45”. And “5/15” in the seconds field means “the seconds 5, 20, 35, and 50”. You can also specify ‘/’ after the ‘’ character - in this case ‘’ is equivalent to having ‘0’ before the ‘/’. ‘1/3’ in the day-of-month field means “fire every 3 days starting on the first day of the month”.
  • L (“last”) - has different meaning in each of the two fields in which it is allowed. For example, the value “L” in the day-of-month field means “the last day of the month” - day 31 for January, day 28 for February on non-leap years. If used in the day-of-week field by itself, it simply means “7” or “SAT”. But if used in the day-of-week field after another value, it means “the last xxx day of the month” - for example “6L” means “the last friday of the month”. You can also specify an offset from the last day of the month, such as “L-3” which would mean the third-to-last day of the calendar month. When using the ‘L’ option, it is important not to specify lists, or ranges of values, as you’ll get confusing/unexpected results.
  • W (“weekday”) - used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify “15W” as the value for the day-of-month field, the meaning is: “the nearest weekday to the 15th of the month”. So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you specify “1W” as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not ‘jump’ over the boundary of a month’s days. The ‘W’ character can only be specified when the day-of-month is a single day, not a range or list of days.

The ‘L’ and ‘W’ characters can also be combined in the day-of-month field to yield ‘LW’, which translates to *“last weekday of the month”*.

  • # - used to specify “the nth” XXX day of the month. For example, the value of “6#3” in the day-of-week field means “the third Friday of the month” (day 6 = Friday and “#3” = the 3rd one in the month). Other examples: “2#1” = the first Monday of the month and “4#5” = the fifth Wednesday of the month. Note that if you specify “#5” and there is not 5 of the given day-of-week in the month, then no firing will occur that month.

The legal characters and the names of months and days of the week are not case sensitive. MON is the same as mon.

Examples

Expression Meaning
0 0 12 * * ? Fire at 12pm (noon) every day
0 15 10 ? * * Fire at 10:15am every day
0 15 10 * * ? Fire at 10:15am every day
0 15 10 * * ? * Fire at 10:15am every day
0 15 10 * * ? 2005 Fire at 10:15am every day during the year 2005
0 * 14 * * ? Fire every minute starting at 2pm and ending at 2:59pm, every day
0 */1 * * * ? Fire every minute starting at 0 second, every day
0 0/5 14 * * ? Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day
0 0/5 14,18 * * ? Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day
0 0-5 14 * * ? Fire every minute starting at 2pm and ending at 2:05pm, every day
0 10,44 14 ? 3 WED Fire at 2:10pm and at 2:44pm every Wednesday in the month of March.
0 15 10 ? * MON-FRI Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday
0 15 10 15 * ? Fire at 10:15am on the 15th day of every month
0 15 10 L * ? Fire at 10:15am on the last day of every month
0 15 10 L-2 * ? Fire at 10:15am on the 2nd-to-last last day of every month
0 15 10 ? * 6L Fire at 10:15am on the last Friday of every month
0 15 10 ? * 6L Fire at 10:15am on the last Friday of every month
0 15 10 ? * 6L 2002-2005 Fire at 10:15am on every last friday of every month during the years 2002, 2003, 2004 and 2005
0 15 10 ? * 6#3 Fire at 10:15am on the third Friday of every month
0 0 12 1/5 * ? Fire at 12pm (noon) every 5 days every month, starting on the first day of the month.
0 11 11 11 11 ? Fire every November 11th at 11:11am.

Generators

Cron Expression Generator - freeformatter

References

[1] cron - Wikipedia

[2] Cron Trigger Tutorial

[3] Scheduling Tasks - Spring

Configuring OS Environments

Configuring Environments on Windows

  1. Add environment variable JAVA_HOME={jdk11_path}.
  2. Add %JAVA_HOME%\bin to the environment variable path.
  3. Verify Java version. $ java -version.
  4. Restart IDE.

Note: After updating the JAVA_HOME environment variable, you need to restart your IDE.

Configuring Maven Project pom.xml

By default your version of Maven might use an old version of the maven-compiler-plugin that is not compatible with Java 9 or later versions. To target Java 9 or later, you should at least use version 3.6.0 of the maven-compiler-plugin and set the maven.compiler.release property to the Java release you are targetting (e.g. 9, 10, 11, 12, etc.). [1]

<properties>
<maven.compiler.release>11</maven.compiler.release>
</properties>

<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>

or

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>

Configuring IDE

Configuring Java 11 for IntelliJ IDEA

  1. Open Project Settings (Ctrl + Shift + Alt + S) –> Project –> Project SDK: 11, Project language level: 11.
  2. Open Settings (Ctrl + Alt + S) –> Build, Execution, Deployment –> Compiler –> Java Compiler –> Project bytecode version: 11

Verification

Running test

$ mvn test

References

[1] Maven in 5 Minutes

CSS Colors

Colors in CSS can be specified by the following methods:

  • Hexadecimal colors
  • Hexadecimal colors with transparency
  • RGB colors
  • RGBA colors
  • HSL colors
  • HSLA colors
  • Predefined/Cross-browser color names
  • With the currentcolor keyword

Hexadecimal Colors

A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color. All values must be between 00 and FF.

For example, the #0000ff value is rendered as blue, because the blue component is set to its highest value (ff) and the others are set to 00.

#p1 {background-color: #ff0000;}   /* red */
#p2 {background-color: #00ff00;} /* green */
#p3 {background-color: #0000ff;} /* blue */

Hexadecimal Colors With Transparency

A hexadecimal color is specified with: #RRGGBB. To add transparency, add two additional digits between 00 and FF.

#p1a {background-color: #ff000080;}   /* red transparency */
#p2a {background-color: #00ff0080;} /* green transparency */
#p3a {background-color: #0000ff80;} /* blue transparency */

RGB Colors

An RGB color value is specified with the rgb() function, which has the following syntax:

rgb(red, green, blue)

Each parameter (red, green, and blue) defines the intensity of the color and can be an integer between 0 and 255 or a percentage value (from 0% to 100%).

For example, the rgb(0,0,255) value is rendered as blue, because the blue parameter is set to its highest value (255) and the others are set to 0.

Also, the following values define equal color: rgb(0,0,255) and rgb(0%,0%,100%).

#p1 {background-color: rgb(255, 0, 0);}   /* red */
#p2 {background-color: rgb(0, 255, 0);} /* green */
#p3 {background-color: rgb(0, 0, 255);} /* blue */

RGBA Colors

RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity of the object.

An RGBA color is specified with the rgba() function, which has the following syntax:

rgba(red, green, blue, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

#p1 {background-color: rgba(255, 0, 0, 0.3);}   /* red with opacity */
#p2 {background-color: rgba(0, 255, 0, 0.3);} /* green with opacity */
#p3 {background-color: rgba(0, 0, 255, 0.3);} /* blue with opacity */

HSL Colors

HSL stands for hue, saturation, and lightness - and represents a cylindrical-coordinate representation of colors.

HSLA Colors

HSLA color values are an extension of HSL color values with an alpha channel - which specifies the opacity of the object.

Predefined/Cross-browser Color Names

140 color names are predefined in the HTML and CSS color specification.

For example: blue, red, coral, brown, etc:

#p1 {background-color: blue;}
#p2 {background-color: red;}
#p3 {background-color: coral;}

The currentcolor Keyword

The currentcolor keyword refers to the value of the color property of an element.

#myDIV {
color: blue; /* Blue text color */
border: 10px solid currentcolor; /* Blue border color */
}

Color Schemes

  • Achromatic Color Schemes
  • Monochromatic Color Schemes. Monochromatic schemes use different tones from the same angle on the color wheel (the same hue).
  • Analogous Color Schemes. Analogous color schemes are created by using colors that are next to each other on the color wheel.
  • Complementary Color Schemes. Complementary schemes are created by combining colors from opposite sides of the color wheel.
  • Triadic. Triadic schemes are made up of hues equally spaced around color wheel.
  • Compound (aka Split Complementary) Color Scheme. Compound schemes are almost the same as complementary schemes. Instead of using colors that are opposites, it uses colors on both sides of the opposite hue.

Color Psychology

  • Colors can influence human behavior.
  • Colors can influence human perceptions.
  • Colors can influence the taste of food.
  • Colors can influence attractiveness.
RED
Red attracts the human eye

Energy: power, strength, excitement.

Danger: fire, blood, urgency, traffic stop.

Passion: appetite, emotion, love.

GREEN
Green is the most restful color

Nature: Fertility, Freshness, New Growth.

Safety: Good Health, Healing Power, Free Traffic.

Harmony: Peace, Easiness, Calmness.

BLUE
Blue is the most used office color

Sea: Water, Ocean, Depth, Wealth.

Quality: Stability, Conservatism, Productivity, Wisdom, Intelligence.

Sky: Truth, Peace, Heaven.

Yellow
Yellow is a Happy Color

Sunshine: Light, Clarity, Energy, Warmth.

Optimism: Happiness, Positivity, Cheerfulness, Youngfulness.

Black
Black is Authority and Mystery

Authority: Power, Elegance, Formality.

Mystery: Evil, Fear, Death.

Gray
Grey is Conservative

Security
Reliability
Classic Knowledge
Professional Wisdom

White
White is Purity
Cleanliness Neutrality Goodness Innocence

Common Colors

  • Color Names Supported by All Browsers
  • Color Groups
  • Color Shades
  • Fashion Color

Color Names Supported by All Browsers

Color Names Supported by All Browsers

Color Groups

HTML Color Groups

2014 Material Design color palettes

The color system - Material Design

Shades of Gray

Gray Shades HEX RGB
HTML Black #000000 rgb(0,0,0)
#080808 rgb(8,8,8)
#101010 rgb(16,16,16)
#181818 rgb(24,24,24)
#202020 rgb(32,32,32)
#282828 rgb(40,40,40)
#303030 rgb(48,48,48)
#383838 rgb(56,56,56)
#404040 rgb(64,64,64)
#484848 rgb(72,72,72)
#505050 rgb(80,80,80)
#585858 rgb(88,88,88)
#606060 rgb(96,96,96)
#686868 rgb(104,104,104)
#696969 rgb(105,105,105)
#707070 rgb(112,112,112)
#787878 rgb(120,120,120)
HTML Gray #808080 rgb(128,128,128)
#888888 rgb(136,136,136)
#909090 rgb(144,144,144)
#989898 rgb(152,152,152)
#A0A0A0 rgb(160,160,160)
#A8A8A8 rgb(168,168,168)
HTML DarkGray !!! #A9A9A9 rgb(169,169,169)
#B0B0B0 rgb(176,176,176)
#B8B8B8 rgb(184,184,184)
X11 Gray #BEBEBE rgb(190,190,190)
HTML Silver #C0C0C0 rgb(192,192,192)
#C8C8C8 rgb(200,200,200)
#D0D0D0 rgb(208,208,208)
HTML LightGray #D3D3D3 rgb(211,211,211)
#D8D8D8 rgb(216,216,216)
HTML Gainsboro #DCDCDC rgb(220,220,220)
#E0E0E0 rgb(224,224,224)
#E8E8E8 rgb(232,232,232)
#F0F0F0 rgb(240,240,240)
HTML WhiteSmoke #F5F5F5 rgb(245,245,245)
#F8F8F8 rgb(248,248,248)
HTML White #FFFFFF rgb(255,255,255)

Colors for Alerts

Display Dangers

Danger!

Red often indicates a dangerous or negative situation.

HEX: #FFDDDD

Danger!

Red often indicates a dangerous or negative situation.

HEX: #F44336

Display Warnings

Warning!

Yellow often indicates a warning that might need attention.

HEX: #FFFFCC

Warning!

Yellow often indicates a warning that might need attention.

HEX: #FFEB3B

Display Successs

Success!

Green often indicates something successful or positive.

HEX: #DDFFDD

Success!

Green often indicates something successful or positive.

HEX: #4CAF50

Display Information

Info!

Blue often indicates a neutral informative change or action.

HEX: #DDFFFF

Info!

Blue often indicates a neutral informative change or action.

HEX: #2196F3

More alert colors

Danger!

Red often indicates a dangerous or negative situation.

HEX: #E91E63

Danger!

Red often indicates a dangerous or negative situation.

HEX: #FF9800

Danger!

Red often indicates a dangerous or negative situation.

HEX: #FF5722

Danger!

Red often indicates a dangerous or negative situation.

HEX: #607D8B

Danger!

Red often indicates a dangerous or negative situation.

HEX: #FFC107

Fashion Colors

2019 - Living Coral
HEX: #FF6F61
PANTONE 16-1546
2018 - Ultra Violet
HEX: #6B5B95
PANTONE 18-3838
2017 Greenery
Hex #88B04B
RGB(136, 176, 75)
Pantone 15-0343
2016 Rose Quartz
Hex #F7CAC9
RGB(247, 202, 201)
Pantone 13-1520
2016 Serenity
Hex #92A8D1
RGB(146, 168, 209)
Pantone 15-3919
2015 Marsala
Hex #955251
RGB(149, 82, 81)
Pantone 18-1438
2014 Radiand Orchid
Hex #B565A7
RGB(181, 101, 167)
Pantone 18-3224
2013 Emerald
Hex #009B77
RGB(0, 155, 119)
Pantone 17-5641
2012 Tangerine Tango
Hex #DD4124
RGB(221, 65, 36)
Pantone 17-1463
2011 Honeysucle
Hex #D65076
RGB(214, 80, 118)
Pantone 18-2120
2010 Turquoise
Hex #45B8AC
RGB(68, 184, 172)
Pantone 15-5510
2009 Mimosa
Hex #EFC050
RGB(239, 192, 80)
Pantone 14-0848
2008 Blue Izis
Hex #5B5EA6
RGB(91, 94, 166)
Pantone 18-3943
2007 Chili Pepper
Hex #9B2335
RGB(155, 35, 53)
Pantone 19-1557
2006 Sand Dollar
Hex #DFCFBE
RGB(223, 207, 190)
Pantone 13-1106
2005 Blue Turquoise
Hex #55B4B0
RGB(85, 180, 176)
Pantone 15-5217
2004 Tigerlily
Hex #E15D44
RGB(225, 93, 68)
Pantone 17-1456
2003 Aqua Sky
Hex #7FCDCD
RGB(127, 205, 205)
Pantone 14-4811
2002 True Red
Hex #BC243C
RGB(188, 36, 60)
Pantone 19-1664
2001 Fuchsia Rose
Hex #C3447A
RGB(195, 68, 122)
Pantone 17-2031
2000 Cerulean Blue
Hex #98B4D4
RGB(152, 180, 212)
Pantone 15-4020

Appendixes

Online Tools

References

CSS Colors

Color Schemes, Psychology

Common Colors

Basics

Types of Boxes

CSS display types (types of boxes):

  • block
  • inline
  • inline-block.
New Line Horizontal Space Actual Width Height Margin Padding
Block elements Always starts on a new line Always occupy the entire horizontal space. 100% by default. You can specify width. Height of content by default. Can specify height. OK OK
Inline elements Don’t start on a new line Width of content. width of content by default. Can’t specify width. Height of content by default. Can’t specify height. Horizontal margin is OK. But vertical margin don’t work. Horizontal padding is OK. But vertical padding don’t occupy space just overlay.
Inline-Block elements Don’t start on a new line Width of content by default. Or specified width. width of content by default. You can specify width. Same with “Block elements” Same with “Block elements” Same with “Block elements”

Height and Width

Width

  • 宽度一般不设置,用内容本身去撑(动态宽度)。也可以设置固定的宽度,使用百分比宽度。
  • 用 padding/margin left/right 百分比,去设置两个元素之间的水平间距。

Height

  • 高度一般也不设置,用内容本身撑(动态高度)。
  • 使用 padding/margin top/bottom 固定值,去增加高度。

Align

Horizontal Align

Horizontally center a div

Horizontally center a div using margin auto
margin: auto;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
}
#innerDiv {
background-color: green;
width: 200px;
height: 200px;
margin: auto;
margin-top: 40px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div>123</div>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
<div>123</div>
</body>
</html>
Horizontally center a div using flexbox in the container
display:flex;
flex-direction:row; /* by default */
justify-content:center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
display:flex;
flex-direction:row; /* by default */
justify-content:center;

}
#innerDiv {
background-color: blue;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
</body>
</html>
Horizontally center a div using transform
/* container */
position: relative;
/* inner div */
position: absolute;
left: 50%;
transform: translate(-50%, 0); /* or transform: translateX(-50%);*/
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container {
position: relative;
height: 400px;
background-color: lightgray;
}

#centeredDiv {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
height: 200px;
width: 200px;
background-color: white;
}
</style>
</head>
<body>
<div id="container">
<div id="centeredDiv">
Content
</div>
</div>
</body>
</html>

Horizontally Center Text

Horizontally center text using text align
text-align: center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#myDiv {
background-color: green;
text-align: center;
}
</style>
</head>
<body>
<div id="myDiv">Content</div>
</body>
</html>
Horizontally center text using flex
display:flex;
flex-direction:row; /* by default */
justify-content:center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#myDiv {
background-color: green;
height: 200px;
display:flex;
flex-direction:row; /* by default */
justify-content:center;
}
</style>
</head>
<body>
<div id="myDiv">Content</div>
</body>
</html>

Align a div to right

Align a div to right using position
position: absolute;
right: 0px;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
position: absolute;
right: 0px;
}
#innerDiv {
background-color: blue;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
</body>
</html>
Align a div to right using float
float: right;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
}
#innerDiv {
background-color: green;
width: 200px;
height: 200px;
float: right;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
</body>
</html>

Align div to left and right

Align a div to left and right using float
<div class="container">
<div class="left-item"></div>
<div class="left-item"></div>
<div class="right-item"></div>
<div class="right-item"></div>
</div>
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.container {
height: 100px;
background-color: gray;
/* fixing overflow outside by adding scroll bar*/
overflow: auto;
}
.container .left-item {
background-color: green;
width: 20%;
height: 200px;
float: left;
margin-right: 10px;
}
.container .right-item {
background-color: blue;
width: 20%;
height: 200px;
float: right;
margin-left: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="left-item">1</div>
<div class="left-item">2</div>
<div class="right-item">3</div>
<div class="right-item">4</div>
</div>
</body>
</html>

Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the “clearfix“ hack to fix this. We can add overflow: auto; to the containing element to fix this problem

Vertical Align

Vertically center a div

Vertically center a div using flexbox in the container

Method 1: using align-items: center

align-items: the direction is across with flex-direction.

display:flex;
flex-direction:row; /* by default*/
align-items:center;

Method 2: using justify-content: center

justify-content: the direction is the same with flex-direction.

display:flex;
flex-direction:column;
justify-content:center;

flex-direction:

  • row (by default, from left to right)
  • row-reverse
  • column (from top to bottom)
  • column-reverse
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
height: 300px;
display:flex;
flex-direction:row; /* by default */
align-items:center;
}
#outerDiv2 {
background-color: lightgray;
height: 300px;
display:flex;
flex-direction:column;
justify-content:center;
}
#innerDiv {
background-color: green;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
<div id="outerDiv2">
<div id="innerDiv">Content</div>
</div>
</body>
</html>
Vertically center a div using transform
/* container */
position: relative;
/* inner div */
position: absolute;
top: 50%;
transform: translate(0, -50%); /* or transform: translateY(-50%);*/
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container {
position: relative;
height: 400px;
background-color: lightgray;
}

#centeredDiv {
position: absolute;
top: 50%;
transform: translate(0, -50%);
height: 200px;
width: 200px;
background-color: white;
}
</style>
</head>
<body>
<div id="container">
<div id="centeredDiv">
Content
</div>
</div>
</body>
</html>

Vertically center text

Vertically center text using line height

Only center a single line text vertically

height: 150px;
line-height: 150px;
Details
<style type="text/css">
#myDiv {
background-color: green;
width: 200px;
height: 150px;
line-height: 150px;
}
</style>

<div id="myDiv">Content</div>
Vertically center text using vertical-align + table-cell

Center multiple lines text vertically

#innerDiv {
display:table-cell;
vertical-align:middle;
}
Details
<style type="text/css">
#myDiv {
background-color: green;
height:400px;
width:150px;
display:table-cell;
vertical-align:middle;
}
</style>

<div id="myDiv">this is multiple lines. this is multiple lines. this is multiple lines. this is multiple lines. this is multiple lines. this is multiple lines. this is multiple lines. </div>
Vertically center text using padding

Using padding in no height a div.

padding-top: 50px;
padding-bottom: 50px;
Details
<style type="text/css">
#myDiv {
background-color: green;
width: 200px;
padding-top: 100px;
padding-bottom: 100px;
}
</style>

<div id="myDiv">Content</div>
Vertically center text using flex
display:flex;
flex-direction:row; /* by default */
align-items:center;
Details
<style type="text/css">
#myDiv {
background-color: blue;
width: 200px;
height: 200px;
display:flex;
flex-direction:row; /* by default */
align-items:center;
}
</style>

<div id="myDiv">Content</div>
Vertically center text by center a inner div vertically

Horizontal and vertical Align

Horizontally and vertically center a div

Using flex
display:flex;
flex-direction:row; /* by default */
justify-content:center;
align-items: center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
height: 500px;
background-color: darkgray;
display:flex;
flex-direction:row; /* by default */
justify-content:center;
align-items: center;
}
#innerDiv {
background-color: blue;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
</body>
</html>
Using transform
/* container */
position: relative;
/* inner div */
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container {
position: relative;
height: 400px;
background-color: lightgray;
}

#centeredDiv {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
height: 200px;
width: 200px;
background-color: white;
}
</style>
</head>
<body>
<div id="container">
<div id="centeredDiv">
Content
</div>
</div>
</body>
</html>

Horizontally and vertically center text

Using flex
display:flex;
flex-direction:row; /* by default */
justify-content:center;
align-items: center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#myDiv {
background-color: green;
height: 200px;
display:flex;
flex-direction:row; /* by default */
justify-content:center;
align-items: center;
}
</style>
</head>
<body>
<div id="myDiv">Content</div>
</body>
</html>

Layout

Multiple div in one line

float:left (or right);
display:inline-block;
display:flex;

Dynamic Layout

Inline elements in a block element auto wrapping lines until decrease to the block minimal width:

min-width: {fixed_value}

Break Word

  • word-break: normal; // newline for words
  • word-break: break-all; // newline for characters
  • word-break: keep-all; // don’t newline
  • word-break: break-word; // newline for words, if a single word over the block width then newline for character. Deprecated. Using word-break: normal and overflow-wrap: anywhere replace word-break: break-word.

Common CSS

first-of-type and first-child

  • xxx:first-of-type: match the first of selector occur from a parent.
  • xxx:nth-of-type(1)
  • xxx:last-of-type
  • xxx:nth-last-of-type(1)
  • xxx:first-child : match when the first of child of a parent is the selector.
  • xxx:nth-child(1)
<div class="column">
<div class="row">I am .row:first-of-child.</div>
<div class="row">this is a lines. </div>
<div class="row">this is a lines. </div>
</div>
<div class="column">
<p>I am p:first-of-child</p>
<div class="row">I am .row:first-of-type not .row:first-of-child.</div>
<div class="row">this is a lines. </div>
<div class="row">this is a lines. </div>
</div>

Classic Layout

Multiple columns align left using display: flex;

<style type="text/css">
#content {
display: flex;
flex-direction: row;
}
.column {
background-color: darkgray;
padding: 20px 20px 20px 0px;
}
.column:first-of-type {
padding-left: 20px
}
.row {
background-color: green;
height: 30px;
margin-top: 10px;
}
.row:first-of-type {
margin-top: 0px;
font-weight: bold;
}
</style>

<div id="content">
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
</div>

Multiple columns align left and one column align right using display: flex; and margin-left: auto;

<style type="text/css">
#content {
background-color: darkgray;
width: 100%;
display: flex;
flex-direction: row;
}
.column {
background-color: orange;
padding: 20px 20px 20px 0px;
}
.column:first-of-type {
padding-left: 20px
}
.column:nth-last-of-type(1) {
background-color: red;
margin-left: auto;
}
.row {
background-color: green;
height: 30px;
margin-top: 10px;
}
.row:first-of-type {
margin-top: 0px;
font-weight: bold;
}
</style>

<div id="content">
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
</div>

columns have two directions, some from align left, others align right, using flex-direction: row and flex-direction: row-reverse;

<style type="text/css">
#content {
background-color: darkgray;
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
}
#section1 {
display: flex;
flex-direction: row;
}
#section2 {
display: flex;
flex-direction: row-reverse;
}
.column {
background-color: orange;
padding: 20px 20px 20px 0px;
}
.column:first-of-type {
padding-left: 20px
}
.column:nth-last-of-type(1) {
background-color: red;
}
.row {
background-color: green;
height: 30px;
margin-top: 10px;
}
.row:first-of-type {
margin-top: 0px;
font-weight: bold;
}
</style>

<div id="content">
<div id="section1">
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
</div>
<div id="section2">
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
</div>
</div>

Common class name

  • row
  • column
  • title
  • content
  • item
  • wrapper
  • menu-bar
  • top, header, footer
  • logo

References

[1] CSS display properties: block, inline, and inline-block — & how to tell the difference

[2] CSS Layout - Horizontal & Vertical Align - w3schools

[3] Aligning Items in a Flex Container

Errors

ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

Solutions

Check InnoDB status for locks

SHOW ENGINE InnoDB STATUS;

Check MySQL open tables

SHOW OPEN TABLES WHERE In_use > 0;

Check pending InnoDB transactions

for kill slow query by view query SQL statement (trx_query)

SELECT * FROM `information_schema`.`innodb_trx` ORDER BY `trx_started`; 

Check lock dependency - what blocks what

for kill locked query

SELECT * FROM `information_schema`.`innodb_locks`;

Show running threads

get query thread ID

SHOW PROCESSLIST;
SELECT * 
FROM information_schema.processlist
WHERE user <> 'system user' and
COMMAND != 'Sleep'and
info like '%SELECT%'
order by `time` desc;
Id	`User`	Host	db	Command	`Time`	State	Info
  • Id: thread ID.
  • db: database name.
  • Command: Query, Sleep(the session is idle).
  • Time: the time in seconds that the thread has been in its current state. For a replica SQL thread, the value is the number of seconds between the timestamp of the last replicated event and the real time of the replica host.
  • Info: the statement the thread is executing, or NULL if it is executing no statement.

Kill Threads By Thread ID

Kill a Particular Thread

KILL {processlist_id};

get kill all your MySQL queries

SELECT GROUP_CONCAT(CONCAT('KILL ',id,';') SEPARATOR ' ') 
FROM information_schema.processlist
WHERE user <> 'system user' and
COMMAND != 'Sleep'and
info like '%SELECT%';
KILL 1; KILL 2;
SELECT CONCAT('KILL ',id,';') AS kill_list 
FROM information_schema.processlist
WHERE user <> 'system user' and
COMMAND != 'Sleep'and
info like '%SELECT%';
+------------------------+
| kill_list |
+------------------------+
| KILL 1; |
| KILL 2; |
+------------------------+

References

[1] Fixing “Lock wait timeout exceeded; try restarting transaction” for a ‘stuck” Mysql table?

[2] How To Kill MYSQL Queries

[3] 26.3.23 The INFORMATION_SCHEMA PROCESSLIST Table - MySQL

[4] 13.7.8.4 KILL Statement - MySQL

The web page language for displaying is:

  • Not determined by your operating system display language.
  • Not determined by your browser display language.
  • Not determined by the HTTP header Accept-Language.

The web page language for display is determined by the preferred language of your browser. The preferred language list of your browser is the same as your operating system display language or browser display language. But you can set to add your custom preferred language and move it to the top of the list.

Chrome

Chrome settings –> Advanced –> Languages –> Order languages based on your preference –> Add languages –> Move your preferred language for displaying to the top.

Firefox

Options –> General –> Language and Appearance –> Language –> Choose your preferred language for displaying pages –> Choose –> Add your language –> Move your preferred language for displaying to the top.

本文将介绍微信支付开发相关内容,微信支付有很多种途径,本文主要以 JSAPI 支付为例。接下来将介绍微信支付的基础和 JSAPI 支付开发过程。

微信支付的基础

微信支付产品

  • 付款码支付:付款码支付是用户展示微信钱包内的“刷卡条码/二维码”给商户系统扫描后直接完成支付的模式。主要应用线下面对面收银的场景。
  • Native 支付:Native支付是商户系统按微信支付协议生成支付二维码,用户再用微信“扫一扫”完成支付的模式。该模式适用于PC网站支付、实体店单品或订单支付、媒体广告支付等场景。
  • JSAPI支付:JSAPI支付是用户在微信中打开商户的H5页面,商户在H5页面通过调用微信支付提供的JSAPI接口调起微信支付模块完成支付。
  • APP支付:APP支付又称移动端支付,是商户通过在移动端应用APP中集成开放SDK调起微信支付模块完成支付的模式。
  • H5支付:H5支付主要是在手机、ipad等移动设备中通过浏览器来唤起微信支付的支付产品。
  • 小程序支付:小程序支付是专门被定义使用在小程序中的支付产品。目前在小程序中能且只能使用小程序支付的方式来唤起微信支付。

以上不同的微信支付产品对应不同的微信支付系统的 API。其中,线上使用的支付方式:JSAPI 支付,APP 支付,H5 支付。对于在微信公众号内的微信支付,一般使用 JSAPI 支付方式。

常见术语名词解释

  • 微信公众平台:微信公众平台是微信公众账号申请入口和管理后台。商户可以在公众平台提交基本资料、业务资料、财务资料申请开通微信支付功能。
  • 微信开放平台:微信开放平台是商户APP接入微信支付开放接口的申请入口,通过此平台可申请微信APP支付。
  • 微信商户平台:微信商户平台是微信支付相关的商户功能集合,包括参数配置、支付数据查询与统计、在线退款、代金券或立减优惠运营等功能。
  • 微信支付系统:微信支付系统是指完成微信支付流程中涉及的API接口、后台业务处理系统、账务系统、回调通知等系统的总称。
  • 商户证书:商户证书是微信提供的二进制文件,商户系统发起与微信支付后台服务器通信请求的时候,作为微信支付后台识别商户真实身份的凭据。
  • 签名:商户后台和微信支付后台根据相同的密钥和算法生成一个结果,用于校验双方身份合法性。签名的算法由微信支付制定并公开,常用的签名方式有:MD5、SHA1、SHA256、HMAC等。
  • Openid:用户在公众号内的身份标识,不同公众号拥有不同的openid。商户后台系统通过登录授权、支付通知、查询订单等API可获取到用户的openid。主要用途是判断同一个用户,对用户发送客服消息、模版消息等。企业号用户需要使用企业号userid转openid接口与openid互换接口)将企业成员的userid转换成openid。

申请开通微信支付功能

微信公众号商户可以在微信公众平台提交开通微信支付的申请,第三方APP商户可以在微信开放平台提交申请。申请提交后,微信支付工作人员审核资料无误将开通相应的微信支付权限。微信支付申请审核通过后,商户在申请资料填写的邮箱中收取到由微信支付小助手发送的邮件,此邮件包含开发时需要使用的支付账户信息。

  • APPID:appid是微信公众账号或开放平台APP的唯一标识,在公众平台申请公众账号或者在开放平台申请APP账号后,微信会自动分配对应的appid,用于标识该应用。
  • 微信支付商户号 mch_id:商户申请微信支付后,由微信支付分配的商户收款账号。
  • API 密钥:交易过程生成签名的密钥,仅保留在商户系统和微信支付后台,不会在网络中传播。商户妥善保管该Key,切勿在网络中传输,不能在其他客户端中存储,保证key不会被泄漏。
  • Appsecret:AppSecret是APPID对应的接口密码,用于获取接口调用凭证access_token时使用。在微信支付中,先通过OAuth2.0接口获取用户openid,此openid用于微信内网页支付模式下单接口使用。
  • 商户平台登录帐号。
  • 商户平台登录密码。

开通微信支付功能后,会得到额外三个用于开发微信支付的参数:mch_id, API 密钥, Appsecret。这三个参数在调用微信支付系统的 API 时需要用到。

微信 JSAPI 支付开发

微信微信 JSAPI 支付开发前提

  • 申请商户的微信支付账号。商户在微信公众平台或开放平台提交微信支付申请,申请成功后可获取其支付账号的相关参数用于微信支付开发。
  • 设置支付目录。1)商户最后请求拉起微信支付收银台的页面地址我们称之为“支付目录”,例如:https://www.weixin.com/pay.php。2)商户实际的支付目录(支付页面URL)必须和在微信支付商户平台设置的一致。3)如果支付授权目录设置为顶级域名(例如:https://www.weixin.com/ ),那么只校验顶级域名,不校验后缀。
  • 设置授权域名。在统一下单接口中要求必传用户openid,即需要进行网页授权,获取用户信息。

微信支付系统主要提供的 API 和功能

  • 支付下单、查询订单、支付结果通知(微信回调)
  • 申请退款、查询退款、退款通知(微信回调)

详细的 API 列表可参考微信支付官方文档:微信支付 API 列表

微信 JSAPI 支付开发需要的参数

  • 商户号(mch_id)
  • API 密钥(key):交易过程用于生成签名的密钥,仅保留在商户系统和微信支付后台。
  • API 证书(application_cert.pem):微信支付接口中,涉及资金回滚的接口会使用到 API 证书,包括退款、撤销接口。证书文件主要用于退款时发送 SSL 请求。
  • 当然还包括公众平台的参数(appId,appSecret)。

其中公众平台的 appId 与微信支付系统的 mch_id 将公众号应用与微信支付帐号进行了绑定。

微信 JSAPI 支付功能的实现过程

  • 用户发起支付请求。
  • 公众号后端,生成商户自己的订单数据(商户订单号),保存到数据库订单表。
  • 调用微信统一下单API,得到预付单信息(prepay_id)。下单成功后更新数据库订单表。
  • 生成公众号页面调用 JSAPI 支付接口需要的参数并签名(paySign),将参数返回给前端页面。
  • 公众号前端页面,调用 JSAPI 支付接口请求支付。
  • 微信支付系统验证参数的合法性,若参数合法则弹出微信的确认支付的页面。用户输入支付密码,密码验证通过后会跳转到微信的支付成功页面,并同时发起微信支付的回调。
  • 在支付成功页面点击返回商家,跳转到商户指定的页面。商户系统后端调用微信订单查询 API,查询支付结果,生成商户自己的支付结果页面。
  • 公众号后端,处理微信支付的回调。进行业务处理后,返回处理结果给微信支付系统。

详细业务流程可参考微信支付官方文档:JSAPI 支付业务流程时序图

公众号网页调用 JSSDK 支付接口(调起微信支付)

可以使用微信 JSSDK 的支付 API。也可以使用微信支付封装的JS方法。

1)JSSDK 发起支付请求

wx.ready(function(
// auto execution
wx.chooseWXPay({
timestamp: 0, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
nonceStr: '', // 支付签名随机串,不长于 32
package: '', // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
signType: '', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: '', // 支付签名
success: function (res) {
// 支付成功后的回调函数
}
});
));

2)微信支付平台封装的方法

<script>
function onBridgeReady(){
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId":"wx2421b1c4370ec43b", //公众号名称,由商户传入
"timeStamp":"1395712654", //时间戳,自1970年以来的秒数
"nonceStr":"e61463f8efa94090b1f366cccfbbb444", //随机串
"package":"prepay_id=u802345jgfjsdfgsdg888",
"signType":"MD5", //微信签名方式:
"paySign":"70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名
},
function(res){
if(res.err_msg == "get_brand_wcpay_request:ok" ){
// 使用以上方式判断前端返回,微信团队郑重提示:
//res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
}
});
}

if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
}
}else{
onBridgeReady();
}
</script>

注意事项

微信支付需要在微信APP中调试,不能在微信开发者工具中调试。

References

[1] 微信支付V2版API接口文档

[2] 微信支付开发文档3.0

介绍微信公众平台

微信公众平台是微信团队为微信公众号开发者提供的一个基础平台,平台通过为公众号开发者提供一系列的接口,让公众号能够更好的为微信用户提供服务。

微信公众号是微信 APP 中的一个功能,它是公众号运营者为微信用户提供资讯和服务的接入点,微信用户通过订阅公众号和进入公众号,可以看到公众号提供的服务菜单和推送消息。

介绍微信公众号开发

如何开发一个公众号

  • 开发者需要在微信公众平台注册一个公众号开发者账号。公众号分为服务号和订阅号,不同类型的公众号具备不同的公众平台的接口权限。
  • 在公众平台配置自己的域名和服务器,开发者的服务器与微信公众平台进行对接。
  • 开发者在微信公众平台提供的接口的基础上开发自己的服务,服务分为两种:公众号消息会话和公众号内网页。

公众号用户的识别

微信用户在公众号内的请求会携带一个 OpenID 的参数,来标识一个用户。每个用户对每个公众号都会产生一个唯一的 OpenID。如果需要在多个公众号之间做用户共通,需要将这些公众号和应用绑定到一个开发平台账号下,绑定后,一个用户对多个公众号依然有多个不同的 OpenID,但一个用户只有一个唯一的 UnionID。

公众号开发注意事项

  • 微信公众平台开发是指微信公众号进行业务开发,为移动应用、PC端网站、公众号第三方平台的开发,请前往微信开发平台接入。
  • 在申请到认证公众号之前,可以先通过测试号申请系统,快速申请一个接口测试号,立即开始接口测试开发。
  • 在开发过程中,可以使用接口调试工具来在线调试某些接口。
  • 每个接口都有每日接口调用频次限制,可以在公众平台官网-开发者中心处查看具体频次。
  • 在开发出现问题时,可以通过接口调用的返回码,以及报警排查指引(在微信公众平台官网-开发者中心处可以设置接口报警),开发发现和解决问题。
  • 公众平台以 access_token 为接口调用凭据,来调用接口,所有接口的调用需要先获取 access_token,access_token 在2小时内有效,过期需要重新获取,但1天内获取次数有限,开发者需自行存储。
  • 公众平台接口调用仅支持80端口。

公众号服务介绍

公众号消息会话

  1. 群发消息:公众号可以以一定频次(订阅号为每天1次,服务号为每月4次),向用户群发消息,包括文字消息、图文消息、图片、视频和语音等。
  2. 被动回复消息:在用户给公众号发消息后,公众号可以自动回复一个消息。
  3. 客服消息:在用户给公众号发消息后的48小时内,公众号可以给用户发送不限数量的消息,主要用于客服场景。
  4. 模板消息:用于给用户发送服务通知,如刷卡提醒,服务预约成功通知等。公众号可以用特定内容模板主动向用户发送。

公众号内网页

许多复杂的业务场景,需要通过网页形式来提供服务,如商城,水电缴费等。公众号网页可以通过点击公众号发送的消息,或者点击公众号菜单进入网页。网页需要用到的公众平台的功能:网页授权获取用户基本信息,微信JS-SDK。

微信公众号开发接入

微信公众号接入是指:部署自己的公众号应用程序到自己的服务器上,然后在微信公众平台配置自己的服务器信息,进行 token 验证,token 验证成功,说明微信公众平台能够正常地与你的服务器进行通信。

微信公众号开发接入过程如下:

  1. 编写公众号应用程序(含验证 token 的接口),服务器启动程序。
  2. 在微信公众平台网站填写服务器配置。在微信公众平台的“开发-基本配置-服务器配置-修改配置”页面,填写服务器的信息。
  3. 验证 token。点击“基本配置页面”下方的提交按钮,进行 token 验证。若当前页面出现“token验证失败”的提示,则说明配置的信息有误,或者你服务器的代码有误;若token验证成功,则会自动返回基本配置的主页面。
  4. 启用配置,准备开发。token 验证成功后,点击“启用”按钮,启用配置的服务器。然后使用微信公众平台提供的接口实现自己业务逻辑。

公众号接入成功后,可以进行微信公众平台 API 的调用测试。主要过程为:编写程序,调用程序,查看程序返回结果。

公众号开发基础

公众平台接口域名

微信公众平台有多个域名,开发者可以根据自己的服务器部署情况,选择最佳的接入点(延时更低,稳定性更高)。除此之外,开发者可以将其他接入点用作容灾用途,当网络链路发生故障时,可以考虑选择备用接入点来接入。微信公众平台的域名如下:

  1. 通用域名(api.weixin.qq.com),使用该域名将访问官方指定就近的接入点;
  2. 通用异地容灾域名(api2.weixin.qq.com),当上述域名不可访问时可改访问此域名;
  3. 上海域名(sh.api.weixin.qq.com),使用该域名将访问上海的接入点;
  4. 深圳域名(sz.api.weixin.qq.com),使用该域名将访问深圳的接入点;
  5. 香港域名(hk.api.weixin.qq.com),使用该域名将访问香港的接入点。

获取 Access token

调用微信公众平台接口之前,必须获取 access_token,access_token 时公众号的全局唯一调用凭据,公众号调用公众平台的接口时都需要使用 access_token 作为参数。

access_token 的存储至少需要保留 512 个字符空间,它的有效期为 2 个小时,需定时刷新,重复获取将导致上次获取的 access_token 失效。

access_token 使用说明:

  • 建议公众号开发者使用中控服务器统一获取和刷新access_token,其他业务逻辑服务器所使用的access_token均来自于该中控服务器,不应该各自去刷新,否则容易造成冲突,导致access_token覆盖而影响业务;
  • 目前access_token的有效期通过返回的expire_in来传达,目前是7200秒之内的值。中控服务器需要根据这个有效时间提前去刷新新access_token。在刷新过程中,中控服务器可对外继续输出的老access_token,此时公众平台后台会保证在5分钟内,新老access_token都可用,这保证了第三方业务的平滑过渡;

接口调用请求:

https请求方式: GET 
URL: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

返回说明:

成功返回信息如下

{"access_token":"ACCESS_TOKEN","expires_in":7200}

IP 白名单

在 IP 白名单内的IP来源,获取 access_token 接口才可调用成功。

接口测试号申请

微信公众平台的某些高级接口的调用权限需要微信认证后才可以获取。为了帮助开发者快速了解和上手微信公众号开发,熟悉各个接口的调用,可以申请微信公众帐号测试号。

微信公众号测试号和你的正式的公众号不是同一个公众号,它们有不同的配置信息,如 appID, appsecret。微信公众号测试号相当于一个虚拟的公众号,可以让你调用很多接口,当你通过测试号实现了你的业务,最后,可以将你的配置参数改为正式的公众号。

测试号不需要设置 IP 白名单,使用测试号的配置信息去调用微信公众平台的接口是没有 IP 限制的。

链接地址:微信公众号接口测试帐号申请

微信公众平台接口在线调试工具

微信公众平台接口在线调试工具,是为了帮助开发者检测调用公众平台 API 时发送的请求参数是否正确。在“在线调试工具”的页面提交相关信息后,提交请求,可获得公众平台服务器的返回结果。

在线调试工具的主要功能是帮你构造参数,其实其它任何地方也可以调用微信公众平台的接口。

链接地址:微信公众平台接口调试工具

Web开发者工具

微信公众平台为开发者提供“web开发者工具”,用于帮助开发基于微信的网页或者webapp。它是一个桌面应用,通过模拟微信客户端的表现使得开发者可以使用这个工具方便地在 PC 上进行开发和调试。

下载地址:web开发者工具

微信公众平台的接口调用和微信公众号内的网页请求

微信公众号的网页,需要在微信公众号内或者在微信web开发者工具中打开。

微信公众平台的接口调用可以在任何支持 HTTP 请求的地方请求并得到返回结果。但“获取access_token 接口”的请求的客户端 IP 需要 IP 白名单中,才能成功返回。然而,调用其它公众平台接口需要 access_token 作为参数,近似相当于没有在 IP 白名单内的客户端请求无法调用微信公众平台接口。不在 IP白名单的客户端的请求结果如下:

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxx&secret=xxx
{"errcode":40164,"errmsg":"invalid ip 58.213.199.30 ipv6 ::ffff:58.213.199.30, not in whitelist hint: [Zhnd8cQNe-4P2DPA]"}

微信公众平台的接口和功能

微信公众平台提供的接口和功能如下:

  • 自定义菜单
  • 消息管理
  • 微信网页开发
  • 素材管理
  • 图文消息留言管理
  • 用户管理
  • 帐号管理
  • 数据统计
  • 微信卡券
  • 微信门店
  • 智能接口
  • 微信设备功能
  • 新版客服功能
  • 对话能力(原导购助手)
  • 微信“一物一码”
  • 微信发票

我们可以简单地将微信公众平台的API接口分为三类:

  • 基础接口(菜单,用户,素材等),为消息服务和网页服务提供基础。
  • 消息服务接口。
  • 网页服务接口。

以上功能的具体的使用步骤和接口调用说明,请参考 微信公众号开发指南

微信网页服务开发

网页授权

网页授权是指:在用户访问公众号网页时获取该微信用户的信息需要先跳转到用户授权页面进行授权。

微信公众号应用需要通过微信用户的 openId 来标识用户,我们需要通过网页授权来获取用户信息,根据用户的 openId 知道是哪个用户访问了公众号网页,然后进行相应的业务处理。

网页授权的过程为:公众号页面重定向跳转到微信用户授权页面,微信回调你的服务器,你获得 code 参数,利用 code 参数获取 JSAPI access_token(与基础 API 的 access_token 不同),利用 access_token 去调用微信 API 获取用户基本信息。

网页授权的实现过程:

  • 在后端定义一个 Filter,拦截所有需要进行网页授权的请求(特定的 URI 前缀),检查请求的 session 中是否存在 openId。如果 openId 不存在,则需要进行网页授权,将未授权的请求重定向到微信授权页面;如果 openId 存在,则不进行任何处理。
  • 微信回调后,你获取到了 code 参数,然后利用 code 参数调用微信 API 获取 access_token 参数,然后利用 access_token 调用微信 API 获取用户基本信息。需要调用两次微信 API。
  • 将微信用户基本保存到 session 中。

JS-SDK使用说明

JS-SDK 功能的页面参考样式:https://www.weixinsxy.com/jssdk/

JS-SDK 接口主要的功能:监听分享事件,暂存音频和视频,调用微信APP的功能(如微信扫一扫、内置地图),微信支付等。

访问测试公众号的网页的条件:

  • 需要在微信开发者工具或者微信APP中访问公众号网页。
  • 需要扫码关注了测试公众号的用户才能访问该公众号网页。
  • 微信公众平台中配置”JS接口安全域名”(公众号调用 JSSDK 的域名),需要备案的域名,而不能是 IP。
  • 微信公众平台中配置“接口权限列表–网页授权获取用户基本信息–授权回调页面域名”(用户授权后回调公众号的域名),需要备案的域名才行。
  • “JS接口安全域名”与“授权回调页面域名”,需要保持一致。
  • (Note: 微信公众平台中配置“Token验证” 的 URL是用于“token 验证”(消息通信是否正常)和“微信公众号的消息服务开发”(消息服务通信的 URL 与 token 验证 的 URL 一致,但消息服务是 HTTP POST 请求),token 验证 URL 与公众号网页服务开发没有关系。消息服务的通信 URL 可以是 IP,可以与网页服务的两个域名不一致)

使用微信 JS-SDK 接口

调用微信 JS-SDK 的 API 接口需要开发者应用提供相关配置和签名参数给 JS-SDK 的配置接口。主要是4个参数:appId,timestamp,nonceStr 和 signature。

获取签名的实现过程:通过普通的 access_token 调用微信 API 获取 jsapi_ticket 参数,生成一个随机字符串(可使用UUID),根据签名算法,将需要4个参数转换为1个签名参数。

JS-SDK 的使用如下:

1)进行权限验证

wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '${wxJsapiConfig.appId}', // 必填,公众号的唯一标识
timestamp: '${wxJsapiConfig.timestamp}', // 必填,生成签名的时间戳
nonceStr: '${wxJsapiConfig.nonceStr}', // 必填,生成签名的随机串
signature: '${wxJsapiConfig.signature}',// 必填,签名
jsApiList: [
'updateAppMessageShareData',
'updateTimelineShareData'
] // 必填,需要使用的JS接口列表
});

2)权限验证成功后,会执行JS-SDK 的 wx.ready() 方法:

wx.ready(function(){
//自定义“分享给朋友”及“分享到QQ”按钮的分享内容
// Auto running
wx.updateAppMessageShareData({
title: 'wxPage-index', // 分享标题
desc: 'Test share to friend.', // 分享描述
link: '${wxJsapiConfig.url}', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: '', // 分享图标
success: function () {
// 设置成功
console.log("Set share to friend info successfully!");
}
})

// 拍照或从手机相册中选图接口
// onclick running
document.querySelector('#chooseImage').onclick = function () {
wx.chooseImage({
count: 9, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
console.log("chooseImage -- localIds first: " + localIds[0]);
}
});
};
});

3)权限验证失败后,会执行 JS-SDK 的 wx.error() 方法。

wx.error(function (res) {
alert(res.errMsg);
});

更多内容请参考官方说明:

微信公众号开发接入示例

下面以 Java 为例,基于 Spring Boot 框架进行示例展示。

1.创建和配置项目

创建一个 Maven 项目,项目名为 wechat-official-accounts

mvn archetype:generate -DgroupId=com.taogen.example -DartifactId=wechat-official-accounts -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

配置 pom.xml 文件

<project ...>  
...

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<!-- custom properties -->
<project.java.version>1.8</project.java.version>
<junit.version>4.12</junit.version>
<log4j.version>2.8.2</log4j.version>
</properties>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>

<dependencies>
<!-- start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- spring web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- unit test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<plugins>
<!-- Package as an executable jar/war. $ mvn package spring-boot:repackage -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- maven compile -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>${project.java.version}</source>
<target>${project.java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

配置 log4j2 日志

src/main/resources/log4j2.xml

<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="com.taogen.example" level="debug" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

配置 Spring Boot 参数和业务参数

src/main/resources/application.yml

wechat:
token: "my_token"
appId: "..."
appSecret: "..."
server:
port: 80

2.编写验证 token 的 Java 代码

src/main/java/com/taogen/example/App.java

@SpringBootApplication
@RestController
public class App {

private static final Logger logger = LogManager.getLogger();
@Value("${wechat.token}")
private String token;
@Value("${wechat.appId}")
private String appId;
@Value("${wechat.appSecret}")
private String appSecret;

public static void main(String[] args) {
SpringApplication.run(App.class, args);
}

@GetMapping("/hello")
public String hello() {
logger.debug("Access /hello");
return "hello " + new Date();
}

/**
* Validate Token
*
* @param signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
* @param timestamp 时间戳
* @param nonce 随机数
* @param echostr 随机字符串
* @return 若确认此次GET请求来自微信服务器,请原样返回echostr参数内容
*/
@GetMapping("/wx")
public String validateToken(@RequestParam("signature") String signature,
@RequestParam("timestamp") String timestamp,
@RequestParam("nonce") String nonce,
@RequestParam("echostr") String echostr) {
logger.debug("signature: {}, timestamp: {}, nonce: {}, echostr: {}",
signature, timestamp, nonce, echostr);
// 开发者通过检验signature对请求进行校验(下面有校验方式)。
// 1)将token、timestamp、nonce三个参数进行字典序排序
// 2)将三个参数字符串拼接成一个字符串进行sha1加密
// 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
String sortedParams = getSortedParams(timestamp, nonce);
String encryptedParams = getEncryptedParams(sortedParams);
if (encryptedParams.equals(signature)) {
return echostr;
} else {
return "error";
}
}

private String getSortedParams(String timestamp, String nonce) {
List<String> params = new ArrayList<>();
params.add(this.token);
params.add(timestamp);
params.add(nonce);
Collections.sort(params, Comparator.naturalOrder());
StringBuilder validateString = new StringBuilder();
for (String param : params) {
validateString.append(param);
}
return validateString.toString();
}

private String getEncryptedParams(String sortedParams) {
MessageDigest crypt = null;
try {
crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(sortedParams.toString().getBytes("UTF-8"));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}

return new BigInteger(1, crypt.digest()).toString(16);
}
}

3.打包项目,部署到服务器,运行项目

打包项目:

mvn package spring-boot:repackage

将项目打包文件上传到服务器,运行以下命令启动项目:

java -jar <project_name>.jar

4.在微信公众平台网站进行 token 验证

  • 访问微信公众平台,注册帐号或扫码登录。

  • 登录后,在左侧的菜单栏选择 “开发” - “基本配置”,点击进入基本配置页面。

  • 进入基本配置页面,在“服务器配置”右侧点击修改配置。填写以下配置,主要是 URL 和 你项目中自定义的 token:

    URL: http://<your_server_ip>/wx
    Token: my_token (项目中自主定义的 token)
    EncodingAESKey: (默认)
    消息加密方式:(默认)
  • 点击修改配置页面的“提交”按钮,若 token 验证成功会自动跳转到基本配置页面;若验证失败会在当前页面弹出错误提示。

Summary

微信基础 API 接口

前提要求

  • 客户端请求的 IP 需要在公众平台的 IP 白名单中。但测试公众号不需要。

不满足前提的错误结果

  • 调用微信 API 接口返回的错误提示:

    {"errcode":40164,"errmsg":"invalid ip <your_ip> ipv6 ::ffff:<your_ip>, not in whitelist hint: [jhCDbOwFE-C.kTAa] rid: 5f2baef3-06a383d9-48b6ee02"}

功能列表

  • 获取 access_token
  • 自定义菜单 (创建、删除、查询等)
  • 素材管理(临时素材、永久素材、图文素材的创建、删除和获取等)
  • 图文消息留言管理
  • 用户管理(用户标签、用户备注名、用户基本信息、用户地理位置等)
  • 帐号管理
  • 数据统计
  • 微信卡券

如何对接

  • 获取 access_token,调用微信 API。

微信消息服务

前提要求

  • token 验证通过。

不满足前提的错误结果

  • 无法收到微信服务器的请求

功能列表

  • 自定义菜单 -事件推送
  • 消息管理 (接收普通消息、接收事件推送、回复消息)
  • 消息管理(群发消息、模板消息、一次性订阅消息)

如何对接

  • 接收来自微信服务器的 token 验证请求,进行 token 验证。
  • 接收来自微信服务器的消息,解析 XML 获取消息内容和用户信息,回复 XML 格式的消息。
  • 获取 access_token,调用微信 API,群发消息给多个用户。

微信网页服务

前提要求

  • 公众号的网页需要在微信开发者工具或者微信APP中访问。
  • 公众号网页的 URL 的域名,JS 安全域名和用户授权回调域名需要一致,且域名已经备案。

不满足前提的错误结果

  • 网页出现下面的提示:

    Oops! Something went wrong:(

功能列表

  • 网页授权
  • 网页开发样式 WeUI
  • JS-SDK (基础接口,分享接口,图像接口,音频接口,智能接口,地理位置)
  • JS-SDK(微信支付)
  • 微信开放标签

如何对接

  • 在网页获取微信用户信息。公众号页面重定向跳转到微信用户授权页面,微信回调你的服务器,获得 code 参数,利用 code 参数获取 JSAPI access_token(与基础 API 的 access_token 不同),利用 access_token 去调用微信 API 获取用户基本信息。
  • 在网页调用微信 JS-SDK 的 API。调用微信 API 获取 jsapi_ticket,根据 jsapi_ticket 构造得到签名,将签名和相关参数返回给前端,前端利用签名和相关参数调用 JS-SDK API。

常见问题

Question: 公众号页面重定到微信用户授权页面(获取 code )时出现错误

微信授权页面错误提示为:Oops! Something went wrong:(

Solution:

确保在微信开发者工具或者微信APP 中打开微信公众号的页面链接,而不是在浏览器打开。

检查配置。微信公众平台的接口权限列表中的“网页授权获取用户信息”行,修改“授权回调页面域名”(不需要加 http:// or https://)

Question: JSAPI 参数错误,无效的签名。

错误提示为:{errMsg: "config:fail,Error: 系统错误,错误码:63002,invalid signature [20200804 16:04:22][]"}

Solution:

检查需要的4个参数(noncestr, jsapi_ticket, timestamp, url)是否不为空,是否正确。

检查签名算法是否正确。

检查访问的页面的 URL 要与传递的 URL 一致。注意传递的 url 是 https://xxx, 访问页面也要是 https://xxx,而不能是 http://xxx

Question: JS-SDK debug 模式没有弹出提示

Solution:

检查 JSSDK 的 js 引用是否正确。如,<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

查看微信开发者工具的 console,JavaScript 代码是否有语法错误。

Appendixes

开发者规范

接口权限说明

全局返回码说明

References

[1] 微信公众号开发指南 - DOC

[2] 微信公众平台

0%