jquery Tool Methods

Source: Internet
Author: User
Tags getscript http authentication shallow copy jquery library

The jquery library provides a jquery object ($), which is itself a constructor that can be used to generate an instance of a jquery object. Once you have an instance, you can invoke many methods for the instance, which define the Jquery.prototype object above (abbreviated as $.FN).

In addition to the method of the instance object, the jquery object itself provides methods (that is, directly above the jquery object), and it is not necessary to generate an instance. Because these methods are similar to the nature of "common tools", we call them "tool methods" (utilities).

Common tool Methods

(1) $.trim

The $.trim method is used to remove the string header and trailing extra spaces.

{% highlight JavaScript%}

$.trim (' hello ')//Hello

{% Endhighlight%}

(2) $.contains

The $.contains method returns a Boolean value that represents whether a DOM element (the second parameter) is a subordinate element of another DOM element (the first parameter).

{% highlight JavaScript%}

$.contains (Document.documentelement, document.body); True

$.contains (Document.body, document.documentelement); False

{% Endhighlight%}

(3) $.each,$.map

The $.each method iterates through the array and object, and then returns the original object. It accepts two parameters, namely the data set and the callback function.

{% highlight JavaScript%}

$.each ([n], function (index, value) {Console.log (index + ":" + value);}); 0:52//1:97

var obj = {p1: "Hello", P2: "World"}; $.each (obj, function (key, value) {Console.log (key + ":" + value);}); P1:hello//P2:world

{% Endhighlight%}

It is important to note that the JQuery object instance also has a each method ($.fn.each), which has the same effect.

The $.map method is also used to iterate over arrays and objects, but it returns a new object.

{% highlight JavaScript%}

var a = ["A", "B", "C", "D", "E"]; A = $.map (A, function (n, i) {return (N.touppercase () + i);}); ["A0", "B1", "C2", "D3", "E4"]

{% Endhighlight%}

(4) $.inarray

The $.inarray method returns the position of a value in the array (starting at 0). Returns 1 if the value is not in the array.

{% highlight JavaScript%}

var a = [1,2,3,4]; $.inarray (4,a)//3

{% Endhighlight%}

(5) $.extend

The $.extend method is used to merge multiple objects into the first object.

{% highlight JavaScript%}

var O1 = {p1: ' A ', P2: ' B '}; var O2 = {p1: ' C '};

$.extend (O1,O2); O1.P1//"C"

{% Endhighlight%}

Another use of $.extend is to generate a new object that inherits the original object. At this point, its first argument should be an empty object.

{% highlight JavaScript%}

var O1 = {p1: ' A ', P2: ' B '}; var O2 = {p1: ' C '};

var o = $.extend ({},o1,o2); O//Object {p1: "C", P2: "B"}

{% Endhighlight%}

By default, the Extend method generates a "shallow copy," which means that if a property is an object or an array, only a pointer to that object or array is generated, not the value. If you want a "deep copy," You can pass in the Boolean value true in the first argument of the Extend method.

{% highlight JavaScript%}

var O1 = {p1:[' a ', ' B ']};

var O2 = $.extend ({},o1); var O3 = $.extend (TRUE,{},O1);

O1.p1[0]= ' C ';

O2.P1//["C", "B"] o3.p1//["A", "B"]

{% Endhighlight%}

In the above code, O2 is a shallow copy, and the O3 is a deep copy. As a result, changing the properties of the original array will change O2, and O3 will not.

(6) $.proxy

The $.proxy method is similar to the Bind method of ECMAScript 5, and can be used to bind a function's context (that is, the This object) and parameters and return a new function.

The main use of Jquery.proxy () is to bind the context object to the callback function.

{% highlight JavaScript%}

var o = {type: ' object ', Test:function (event) {Console.log (This.type);}};

$ ("#button"). On ("click", O.test)//No output. On ("Click", $.proxy (O.test, O))//Object

{% Endhighlight%}

In the above code, the first callback function does not have a binding context, so the result is empty and there is no output; the second callback function binds the context to object o, and the result is object.

Another equivalent notation for this example is:

{% highlight JavaScript%}

$ ("#button"). On ("Click", $.proxy (o, test))

{% Endhighlight%}

The $.proxy (o, test) of the above code means that the O method test is bound to O.

This example shows that the proxy method is written in two main ways.

{% highlight JavaScript%}

Jquery.proxy (function, context)

Or

Jquery.proxy (context, name)

{% Endhighlight%}

The first is to specify a context object for a function (functions), and the second is to specify the context object and its method name (name).

Let's look at an example. Under normal circumstances, the this object in the following code points to the DOM object where the Click event occurs.

{% highlight JavaScript%}

$ (' #myElement '). Click (function () {$ (this). addclass (' Anewclass ');});

{% Endhighlight%}

If we want the callback function to run lazily, using the SetTimeout method, the code will go wrong because settimeout makes the callback function run in the global environment and this will point to the global object.

{% highlight JavaScript%}

$ (' #myElement '). Click (function () {setTimeout (function () {$ (this). addclass (' Anewclass ');}, 1000);});

{% Endhighlight%}

This in the code above will point to the Global Object window, resulting in an error.

At this point, you can bind the this object to the MyElement object by using the proxy method.

{% highlight JavaScript%}

$ (' #myElement '). Click (function () {setTimeout ($.proxy () () {$ (this). addclass (' Anewclass ');}, this), 1000);});

{% Endhighlight%}

(7) $.data,$.removedata

The $.data method can be used to store data on a DOM node.

{% highlight JavaScript%}

Deposit Data $.data (document.body, "foo", 52);

Read Data $.data (document.body, "foo");

Read all data $.data (document.body);

{% Endhighlight%}

The above code stores a key-value pair on the body of the page element, with the key named "Foo", with a key value of 52.

The $.removedata method is used to remove the data stored by the $.data method.

{% highlight JavaScript%}

$.data (Div, "test1", "VALUE-1"); $.removedata (Div, "test1");

{% Endhighlight%}

(8) $.parsehtml,$.parsejson,$.parsexml

The $.parsehtml method is used to parse a string into a DOM object.

The $.parsejson method is used to parse a JSON string into a JavaScript object, similar to the native Json.parse (). However, jquery does not provide a method like json.stringify () that does not provide a way to convert a JavaScript object to a JSON object.

The $.parsexml method is used to parse a string into an XML object.

{% highlight JavaScript%}

var html = $.parsehtml ("Hello, my name is jQuery."); var obj = $.parsejson (' {' name ': ' John '} ');

var xml = ""; var xmldoc = $.parsexml (XML);

{% Endhighlight%}

(9) $.makearray

The $.makearray method converts an array-like object into a real array.

{% highlight JavaScript%}

var a = $.makearray (document.getElementsByTagName ("div"));

{% Endhighlight%}

(Ten) $.merge

The $.merge method is used to merge an array (the second argument) into another array (the first parameter).

{% highlight JavaScript%}

var a1 = [0,1,2]; var a2 = [2,3,4]; $.merge (A1, a2);

A1//[0, 1, 2, 2, 3, 4]

{% Endhighlight%}

(one) $.now

The $.now method returns the number of milliseconds that corresponds to the current time distance of January 1, 1970 00:00:00 UTC, equivalent to (new Date). GetTime ().

{% highlight JavaScript%}

$.now ()//1388212221489

{% Endhighlight%}

Methods for judging data types

jquery provides a series of tool methods to determine the data type to compensate for the lack of native typeof operators for JavaScript. The following method determines the parameters and returns a Boolean value.

    • Jquery.isarray (): is an array.
    • Jquery.isemptyobject (): Is an empty object (with no enumerable properties).
    • Jquery.isfunction (): is a function.
    • Jquery.isnumeric (): Whether it is a numeric value (integer or floating point number).
    • Jquery.isplainobject (): Is the object that was generated using "{}" or "new object" instead of the object provided by the native browser.
    • Jquery.iswindow (): Is the Window object.
    • Jquery.isxmldoc (): Determines whether a DOM node is in an XML document.

Here are some examples.

{% highlight JavaScript%}

$.isemptyobject ({})//True $.isplainobject (Document.location)//False $.iswindow (window)//True $.isxmldoc ( Document.body)//False

{% Endhighlight%}

In addition to these methods, there is a $.type method that returns the data type of a variable. The essence of this is to use the Object.prototype.toString method to read the [[Class]] attribute inside the object (see the "Object" section of the standard library).

{% highlight JavaScript%}

$.type (/test/)//"RegExp"

{% Endhighlight%}

Ajax Operation $.ajax

The jquery object also defines the Ajax method ($.ajax ()), which is used to handle AJAX operations. When the method is called, the browser issues an HTTP request to the server.

There are two main ways to use $.ajax ().

$.ajax (url[, Options]) $.ajax ([options])

The URL in the above code refers to the server URL, options is an object parameter, set the specific parameters of the AJAX request.

function successCallback(json) 

The object parameter of the above code has several properties, meaning the following:

  • Accepts: Tell the server what type of data the machine can handle.
  • Async: The item defaults to True, and if set to False, indicates that a synchronization request is being made.
  • Beforesend: Specifies the function to be called before the request is made, and is typically used to modify the emitted data.
  • Cache: The item defaults to True, and if set to False, the browser does not cache the data returned by the server. Note that the browser itself does not cache the data returned by the POST request, so even if set to false, only the head and get requests are valid.
  • Complete: Specifies the callback function at the end of the HTTP request (the callback function for which the request succeeded or failed, at which point it has been run). The callback function executes regardless of the success or failure of the request. Its parameters are the original object that made the request and the status information returned.
  • ContentType: The type of data sent to the server.
  • Context: Specifies an object that acts as the This object for all AJAX-related callback functions.
  • Crossdomain: This property is set to true to force a cross-domain request (such as JSONP) to be sent to the same domain name.
  • Data: To the server, if the Get method is used, the item will be converted to a query string appended to the end of the URL.
  • DataType: The type of data requested from the server, which can be set to text, HTML, script, JSON, JSONP, and XML.
  • Error: The callback function when the request failed, the function parameter is the original object that made the request, and the status information returned.
  • Headers: Specifies the header information for the HTTP request.
  • Ifmodified: If this property is set to True, this request is made only when the server-side content is not the same as the last request.
  • JSONP: Specify JSONP request "callback=?" The name of the callback in.
  • Jsonpcallback: Specifies the name of the callback function in the JSONP request.
  • MimeType: Specifies the MIME type of the HTTP request.
  • Password: Specifies the password required for HTTP authentication.
  • StatusCode: Value is an object that specifies a special callback function for the status code returned by the server.
  • Success: callback function when the request succeeds, the function parameter is the data returned by the server, the state information, the original object that made the request.
  • Timeout: The maximum number of milliseconds to wait. If the request has not returned after this time, the request status is automatically changed to failed.
  • Type: The HTTP verb used to send information to the server, default to get, and other verbs to post, PUT, DELETE.
  • URL: server-side URL. This is the only required property, and all other properties can be omitted.
  • Username: Specifies the user name for HTTP authentication.
  • XHR: Specifies the callback function when the XMLHttpRequest object is generated.

Among these parameters, the URL can be independent, as the first parameter of the Ajax method. In other words, the above code can also be written as follows.

{% highlight JavaScript%}

$.ajax ('/url/to/json ', {type: ' GET ', DataType: ' json ', Success:successcallback, error:errorcallback})

{% Endhighlight%}

The Data property can also be written as an object as it is sent to the server.

$.ajax ({URL:'/remote/url ', data: {param1: ' value1 ', param2: ' value2 ', ...}}; //equivalent to $.ajax ({url: '/remote/url?param1=value1&param2=value2 ... '}}); Simple notation

Ajax methods have some simple ways to do it.

    • $.get (): Issue a GET request.
    • $.getscript (): Reads a JavaScript script file and executes it.
    • $.getjson (): Sends a GET request to read a JSON file.
    • $.post (): Issue a POST request.
    • $.fn.load (): reads an HTML file and puts it into the current element.

In general, these simple methods accept three parameters in turn: URL, data, and a callback function at the time of success.

(1) $.get (), $.post ()

These two methods correspond to the Get method and the post method of HTTP respectively.

{% highlight JavaScript%}

$.get ('/data/people.html ', function (HTML) {$ (' #target '). HTML (HTML);});

$.post ('/data/save ', {name: ' Rebecca '}, function (resp) {Console.log (Json.parse (RESP));});

{% Endhighlight%}

The Get method and the Post method have the same parameters, the first parameter is the server URL, the parameter is required, and the other parameters are optional. The second parameter is the data sent to the server, and the third parameter is the callback function after the successful operation.

The above post method corresponds to the AJAX notation as follows.

{% highlight JavaScript%}

$.ajax ({type: ' POST ', url: '/data/save ', data: {name: ' Rebecca '}, DataType: ' JSON ', success:function (resp) {Console.log (Json.parse (RESP)); } });

{% Endhighlight%}

(2) $.getjson ()

Another handy way to approach Ajax is the Getjson method. When the server side returns JSON-formatted data, this method can be used instead of the $.ajax method.

{% highlight JavaScript%}

$.getjson (' Url/to/json ', {' A ': 1}, function (data) {Console.log (data);});

{% Endhighlight%}

The above code is equivalent to the following notation.

{% highlight JavaScript%}

$.ajax ({dataType: "json", url: '/url/to/data ', data: {' A ': 1}, Success:function (data) {Console.log (data)});

{% Endhighlight%}

(3) $.getscript ()

The $.getscript method is used to load a script file from the server side.

{% highlight JavaScript%}

$.getscript ('/static/js/myscript.js ', function () {functionfrommyscript ();});

{% Endhighlight%}

The above code first loads the Myscript.js script from the server and executes the function provided by the script in the callback function.

Getscript's callback function accepts three parameters, namely the contents of the script file, the status information of the HTTP response, and the Ajax object instance.

{% highlight JavaScript%}

$.getscript ("Ajax/test.js", function (data, textstatus, JQXHR) {console.log (data);//test.js content Console.log (Textstatu s); Success Console.log (jqxhr.status); 200});

{% Endhighlight%}

Getscript is a handy way to use Ajax methods, so it returns a deferred object that can be used with the deferred interface.

{% highlight JavaScript%}

Jquery.getscript ("/path/to/myscript.js"). Done (function () {//...}). Fail (function () {//...});

{% Endhighlight%}

(4) $.fn.load ()

$.fn.load is not a tool method for jquery, but rather a method defined on a jquery object instance that gets the server-side HTML file and puts it into the current element. Because this method also belongs to Ajax operations, so put it together here.

{% highlight JavaScript%}

$ (' #newContent '). Load ('/foo.html ');

{% Endhighlight%}

The $.fn.load method can also specify a selector, place the part of the remote file that matches the selector into the current element, and specify the callback function when the operation completes.

{% highlight JavaScript%}

$ (' #newContent '). Load ('/foo.html #myDiv h1:first ', function (HTML) {console.log (' content update! ‘); });

{% Endhighlight%}

The above code loads only the portion of foo.html that matches the "#myDiv H1:first", and the specified callback function runs when the load is complete.

function(event) 

The above code will specify that the page matches "#main *" and load into the current main element. The asterisk indicates that all child elements contained in the main element are matched, and if the asterisk is not added, the entire main element (including itself) is loaded, resulting in another main element in one main element.

The Load method can append a string or an object as an argument to the server for submission. If it is a string, it is committed with the Get method, and if it is an object, it is submitted using the Post method.

function() 

The above code will be { limit: 25 } submitted to the server via the Post method.

The callback function of the Load method, which can be used to prompt the user that the operation has been completed.

function(event) 
Ajax Events

jquery provides some of the following methods for specifying callback functions for specific AJAX events.

    • . Ajaxcomplete (): Ajax request completed.
    • . Ajaxerror (): An error occurred with the AJAX request.
    • . Ajaxsend (): Before the AJAX request is issued.
    • . Ajaxstart (): The first AJAX request begins to emit, i.e. no AJAX request has yet been completed.
    • . Ajaxstop (): After all AJAX requests have been completed.
    • . Ajaxsuccess (): After the AJAX request succeeds.

The following is an example.

function ()

The following is an example of an error in processing an AJAX request (returning a 404 or 500 error).

function (e, xhr, settings, error) 
return value

The Ajax method returns a deferred object that can be assigned a callback function for the object using the then method (see the Deferred object section for a detailed explanation).

{% highlight JavaScript%}

$.ajax ({url: '/data/people.json ', DataType: ' JSON '}). Then (function (RESP) {console.log (resp.people);})

{% Endhighlight%}

JSONP

Because there is a "same domain restriction" in the browser, the Ajax method can only make HTTP requests to the domain name where the current page resides. However, by inserting a SCRIPT element (<script>) into the current Web page, you can make a GET request to a different domain name, which is called JSONP (JSON with Padding).

The Ajax method can issue a JSONP request by specifying datatype as JSONP in the object parameter.

{% highlight JavaScript%}

$.ajax ({url: '/data/search.jsonp ', data: {q: ' A '}, DataType: ' Jsonp ', success:function (RESP) {$ (' #target '). HTML (' Resul TS: ' + resp.results.length); } });)

{% Endhighlight%}

The usual practice of JSONP is to add the name of the callback function after the URL that you want to request. The Ajax method stipulates that if the requested URL is similar to "callback=?" , the Jsonp form is automatically used. Therefore, the above code can also be written as follows.

{% highlight JavaScript%}

$.getjson ('/data/search.jsonp?q=a&callback=? ', function (RESP) {$ (' #target '). html (' Results: ' + Resp.results.length); } );

{% Endhighlight%}

File Upload

Assume that a Web page has a file control.

<input type="file" id="Test-input" >

Here's how to upload a file using Ajax.

var file = $ (' #test-input ') [0].files[0]; var formData = New FormData (), Formdata.append (' file ', file), $.ajax (' myserver/uploads ', {method: ' POST ', ContentType: false, ProcessData: false, Data:formdata});

The above code sends the file as form data. In addition, you can also send files directly.

var file = $ (' #test-input ') [0].files[0]; $.ajax (' myserver/uploads ', {method: ' POST ', ContentType:file.type, ProcessData: false, data:file}); Reference links
    • David Walsh, Loading Scripts with JQuery
    • Nguyen Huu Phuoc, best jQuery practices

jquery Tool Methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.