Common JavaScript script Summary (1) _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces the first series of common JavaScript scripts, we will share with you that jquery restricts text boxes to only enter numbers, encapsulate DOMContentLoaded events, use native JS for simple encapsulation of AJAX, and format cross-origin requests in JSONP and kilobytes, for more information, see. This article mainly introduces the first series of common JavaScript scripts, we will share with you that jquery restricts text boxes to only enter numbers, encapsulate DOMContentLoaded events, use native JS for simple encapsulation of AJAX, and format cross-origin requests in JSONP and kilobytes, for more information, see.

Jquery restricts that only numbers can be entered in the text box.

Jquery restricts that only numbers can be entered in the text box. It is compatible with IE, chrome, and FF (with different effects). The sample code is as follows:

$ ("Input"). keyup (function () {// keyup event processing
$ (This). val ($ (this). val (). replace (/\ D | ^ 0/g ,''));
}). Bind ("paste", function () {// CTR + V event processing
$ (This). val ($ (this). val (). replace (/\ D | ^ 0/g ,''));
}).Css ("ime-mode", "disabled"); // the CSS setting input method is unavailable.

The above code is used to enter only positive integers greater than 0.

$ ("# Rnumber"). keyup (function (){
$ (This). val ($ (this). val (). replace (/[^ 0-9.]/g ,''));
}). Bind ("paste", function () {// CTR + V event processing
$ (This). val ($ (this). val (). replace (/[^ 0-9.]/g ,''));
}).Css ("ime-mode", "disabled"); // the CSS setting input method is unavailable.

The function of the above Code is: only 0-9 numbers and decimal points can be entered.

Encapsulate DOMContentLoaded events

// Save the domReady event queue
EventQueue = [];
// Determine whether the DOM has been loaded
IsReady = false;
// Determine whether DOMReady is bound
IsBind = false;
/* Execute domReady ()
*
* @ Param {function}
* @ Execute pushes the event handler to the event queue and binds the DOMContentLoaded
* If the DOM loading is complete, execute it immediately.
* @ Caller
*/
Function domReady (fn ){
If (isReady ){
Fn. call (window );
}
Else {
EventQueue. push (fn );
};
BindReady ();
};
/* DomReady event binding
*
* @ Param null
* @ Execute modern browser bind DOMContentLoaded through addEvListener, including ie9 +
The ie6-8 checks doScroll to determine whether DOM is loaded.
* @ Caller domReady ()
*/
Function bindReady (){
If (isReady) return;
If (isBind) return;
IsBind = true;
If (window. addEventListener ){
Document. addEventListener ('domainloaded', execFn, false );
}
Else if (window. attachEvent ){
DoScroll ();
};
};
/* DoScroll determine whether DOM loading of the ie6-8 is complete
*
* @ Param null
* @ Execute doScroll judge whether DOM loading is complete
* @ Caller bindReady ()
*/
Function doScroll (){
Try {
Document.doc umentElement. doScroll ('left ');
}
Catch (error ){
Return setTimeout (doScroll, 20 );
};
ExecFn ();
};
/* Execution event queue
*
* @ Param null
* @ Execute the event handler in the cyclic execution queue
* @ Caller bindReady ()
*/
Function execFn (){
If (! IsReady ){
IsReady = true;
For (var I = 0; I <eventQueue. length; I ++ ){
EventQueue [I]. call (window );
};
EventQueue = [];
};
};
// Js File 1
DomReady (function (){
});
// Js file 2
DomReady (function (){
});
// Note: if Javascript is asynchronously loaded, do not bind the domReady method. Otherwise, the function will not be executed,
// Because DOMContentLoaded has been triggered before the asynchronous loading js download, and the addEventListener cannot be listened to during execution

Simple encapsulation of AJAX using native JS

First, we need xhr objects. This is not difficult for us to encapsulate it into a function.

Var createAjax = function (){
Var xhr = null;
Try {
// IE browser
Xhr = new ActiveXObject ("microsoft. xmlhttp ");
} Catch (e1 ){
Try {
// Non-IE browser
Xhr = new XMLHttpRequest ();
} Catch (e2 ){
Window. alert ("your browser does not support ajax. Please change it! ");
}
}
Return xhr;
};

Then, let's write core functions.

Var ajax = function (conf ){
// Initialization
// Type parameter, optional
Var type = conf. type;
// Url parameter, required
Var url = conf. url;
// The data parameter is optional and is only required for post requests.
Var data = conf. data;
// Optional datatype Parameters
Var dataType = conf. dataType;
// Callback function optional
Var success = conf. success;
If (type = null ){
// Optional. The default value is get.
Type = "get ";
}
If (dataType = null ){
// Optional. The default value is text.
DataType = "text ";
}
// Create an ajax engine object
Var xhr = createAjax ();
// Open
Xhr. open (type, url, true );
// Send
If (type = "GET" | type = "get "){
Xhr. send (null );
} Else if (type = "POST" | type = "post "){
Xhr. setRequestHeader ("content-type ",
"Application/x-www-form-urlencoded ");
Xhr. send (data );
}
Xhr. onreadystatechange = function (){
If (xhr. readyState = 4 & xhr. status = 200 ){
If (dataType = "text" | dataType = "TEXT "){
If (success! = Null ){
// Plain text
Success (xhr. responseText );
}
} Else if (dataType = "xml" | dataType = "XML "){
If (success! = Null ){
// Receives xml documents
Success (xhr. responseXML );
}
} Else if (dataType = "json" | dataType = "JSON "){
If (success! = Null ){
// Convert a json string to a js object
Success (eval ("(" + xhr. responseText + ")"));
}
}
}
};
};

Finally, describe the usage of this function.

Ajax ({
Type: "post ",
Url: "test. jsp ",
Data: "name = dipoo & info = good ",
DataType: "json ",
Success: function (data ){
Alert (data. name );
}
});

JSONP for cross-origin requests


/**
* Added the processing of request failures. Although this function is not very useful, it studies the differences in scripts in various browsers.
* 1. IE6/7/8 supports the onreadystatechange event of scripts.
* 2. IE9/10 supports the onload and onreadystatechange events of scripts.
* 3. Firefox/Safari/Chrome/Opera supports onload events of scripts.
* 4. IE6/7/8/Opera does not support onerror events of scripts; IE9/10/Firefox/Safari/Chrome supports
* 5. Although Opera does not support onreadystatechange events, it has the readyState attribute. This is amazing.
* 6. Use IE9 and IETester to test IE6/7/8. The readyState is always loading and loaded. No complete exists.
*
* The final implementation logic is as follows:
* 1. IE9/Firefox/Safari/Chrome successfully calls back the onload event, and the error callback uses the onerror event.
* 2. for successful callback of Opera, the onload event is also used (it does not support onreadystatechange at all). Because it does not support onerror, latency processing is used here.
* Waiting and successful callback success. After success, the flag done is set to true. Failure will not be executed; otherwise, it will be executed.
* The delay value here is very skillful. It took 2 seconds before and it was okay for the company to test. However, when I went home to use a 3G wireless network, I found that even if the referenced js file exists
* The network speed is too slow. failure is executed first, and then success is executed. So it is reasonable to take 5 seconds here. Of course it is not absolute.
* 3. When the onreadystatechange event is successfully called back in IE6/7/8, the error callback is hardly implemented. It is also the most technical.
* Reference #
* NextSibling cannot be used.
* It is disgusting that even if the requested resource file does not exist. Its readyState also goes through the "loaded" state. In this way, you cannot distinguish whether the request succeeds or fails.
* If you are afraid of it, use the forward and back-end coordination mechanism to solve the final problem. Call callback (true) whether the request succeeds or fails ).
* At this time, the logic of the difference between success and failure has been put into callback. If no jsonp is returned in the background, failure is called; otherwise, success is called.
*
*
* Interface
* Sjax. load (url ,{
* Data // request parameter (key-Value Pair string or js object)
* Success // callback function for successful request
* Failure // callback function for request failure
* Scope // callback function execution Context
* Timestamp // whether to add a timestamp
*});
*
*/
Sjax =
Function (win ){
Var ie678 =! -[1,],
Opera = win. opera,
Doc = win.doc ument,
Head = doc. getElementsByTagName ('head') [0],
Timeout = 3000,
Done = false;
Function _ serialize (obj ){
Var a = [], key, val;
For (key in obj ){
Val = obj [key];
If (val. constructor = Array ){
For (var I = 0, len = val. length; I A. push (key + '=' + encodeURIComponent (val [I]);
}
} Else {
A. push (key + '=' + encodeURIComponent (val ));
}
}
Return a. join ('&');
}
Function request (url, opt ){
Function fn (){}
Var opt = opt | {},
Data = opt. data,
Success = opt. success | fn,
Failure = opt. failure | fn,
Scope = opt. scope | win,
Timestamp = opt. timestamp;
If (data & typeof data = 'object '){
Data = _ serialize (data );
}
Var script = doc. createElement ('script ');
Function callback (isSucc ){
If (isSucc ){
If (typeof jsonp! = 'Undefined') {// The jsonp on the right of the value must be returned by the background. This variable is a global variable.
Done = true;
Success. call (scope, jsonp );
} Else {
Failure. call (scope );
// Alert ('Warning: jsonp did not return .');
}
} Else {
Failure. call (scope );
}
// Handle memory leak in IE
Script. onload = script. onerror = script. onreadystatechange = null;
Jsonp = undefined;
If (head & script. parentNode ){
Head. removeChild (script );
}
}
Function fixOnerror (){
SetTimeout (function (){
If (! Done ){
Callback ();
}
}, Timeout );
}
If (ie678 ){
Script. onreadystatechange = function (){
Var readyState = this. readyState;
If (! Done & (readyState = 'loaded' | readyState = 'complete ')){
Callback (true );
}
}
// FixOnerror ();
} Else {
Script. onload = function (){
Callback (true );
}
Script. onerror = function (){
Callback ();
}
If (opera ){
FixOnerror ();
}
}
If (data ){
Url + = '? '+ Data;
}
If (timestamp ){
If (data ){
Url + = '& ts = ';
} Else {
Url + = '? Ts ='
}
Url + = (new Date). getTime ();
}
Script. src = url;
Head. insertBefore (script, head. firstChild );
}
Return {load: request };
} (This );

The call method is as follows:

Sjax. load ('json66. js ',{
Success: function () {alert (jsonp. name )},
Failure: function () {alert ('error ');}
});

Shard formatting

Function toThousands (num ){
Var num = (num | 0). toString (), result = '';
While (num. length> 3 ){
Result = ',' + num. slice (-3) + result;
Num = num. slice (0, num. length-3 );
}
If (num) {result = num + result ;}
Return result;
}

The above is a common javascript script shared in this article. I hope you will like it.

Related Article

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.