More questions have been collected by me all the way, and there are also previous years. The answers are not guaranteed to be correct. If there are any errors or better solutions, please correct them.
Attached the second article: 2014 front-end written test interview questions for BAT and major Internet companies--Html, Css
The previous questions will be very basic and the more you go, the more you will be, the more you will be in-depth.
Junior Javascript:
1. What kind of language is JavaScript and what are its characteristics?
There is no standard answer.
2.What are the data types of JavaScript?
Basic data types: String, boolean, Number, Undefined, Null
Reference data type: Object(Array,Date,RegExp,Function)
So the question is, how to determine whether a variable is an array data type?
•Method 1. Determine whether it has "array properties", such as the slice() method. You can define the slice method for this variable yourself, so it sometimes fails
• Method 2.obj instanceof Array is incorrect in some IE versions
•Method 3. There are vulnerabilities in both methods. The new method Array.isArray() is defined in ECMA Script5 to ensure its compatibility. The best method is as follows
if(typeof Array.isArray==="undefined") { Array.isArray = function(arg){ return Object.prototype.toString.call(arg)==="[object Array]" }; }3. In the Input input box with a known ID, I hope to get the input value of this input box. How to do it? (No third-party framework)
The code copy is as follows: document.getElementById("ID").value
4. How to get all checkboxes on the page? (No third-party framework)
var domList = document.getElementsByTagName('input')var checkBoxList = [];var len = domList.length; //Cache to local variable while (len--) { //Use while will be more efficient than for loop if (domList[len].type == 'checkbox') { checkBoxList.push(domList[len]); }}5. Set the html content of a DIV with a known ID to xxxx, and the font color is set to black (no third-party frames)
The code copy is as follows:
var dom = document.getElementById("ID");
dom.innerHTML = "xxxx"
dom.style.color = "#000"
6. When a DOM node is clicked, we hope to be able to execute a function. What should we do?
• Bind events directly in the DOM: <div onclick=”test()”></div>
• Binding through onclick in JS: xxx.onclick = test
• Binding by event addition: addEventListener(xxx, 'click', test)
So the question is, what are the event stream models of Javascript?
• "Event Bubble": Events begin to be accepted by the most specific elements and then spread upward step by step
• "Event Capture": Events are received first by the least specific node, and then down step by step, all the way to the most specific one
•"DOM Event Flow": Three stages: Event Capture, Target Stage, Event Bubble
7. What are Ajax and JSON, their pros and cons.
Ajax is asynchronous JavaScript and XML for implementing asynchronous data interaction in web pages.
advantage:
•Can the page load local content without overloading all content, reducing the amount of data transmission
• Avoid users constantly refreshing or jumping pages to improve user experience
shortcoming:
• Not friendly to search engines (
•The cost of implementing the front and back functions under ajax is high
•May cause an increase in the number of requests
• Cross-domain issue restrictions
JSON is a lightweight data exchange format, a subset of ECMA
Advantages: Lightweight, easy to read and write by people, easy to parse by machines (JavaScript), and supports composite data types (arrays, objects, strings, numbers)
8. See what the output of the following code is? Explain the reason.
The code copy is as follows:
var a;
alert(typeof a); // undefined
alert(b); // Report an error
Explanation: Undefined is a data type with only one value. This value is "undefined". When a variable is declared using var but its assignment is not initialized, the value of this variable is undefined. And b will report an error because it is not declared. Note that undeclared variables are different from those declared unassigned.
9. Look at the following code, what outputs? Explain the reason.
The code copy is as follows:
var a = null;
alert(typeof a); //object
Explanation: null is a data type with only one value, and this value is null. It indicates that a null pointer is targeted, so using typeof detection will return "object".
10. Look at the following code, what outputs? Explain the reason.
var undefined;undefined == null; // true1 == true; // true2 == true; // false0 == false; // true0 == ''; // trueNaN == NaN; // false[] == false; // true[] == ![]; // true
•undefined is equal to null, but not identical (===)
• When one is number and the other is string, it will try to convert the string to number
•Try to convert boolean to number, 0 or 1
•Try to convert the Object to number or string, depending on the type of another comparison quantity
• Therefore, for the judgment of 0 and empty strings, it is recommended to use "===" . "===" will first determine the value types on both sides, and it will be false if the types do not match.
So the question is, look at the following code, what output is, and why is the type of foo?
The code copy is as follows:
var foo = "11"+2-"1";
console.log(foo);
console.log(typeof foo);
After execution, the value of foo is 111 and the type of foo is Number.
The code copy is as follows:
var foo = "11"+2+"1"; //Experience the difference between adding a string '1' and subtracting a string '1'
console.log(foo);
console.log(typeof foo); After execution, the value of foo is 1121 (here is string splicing), and the type of foo is String.
11. Look at the code to give the answer.
The code copy is as follows:
var a = new Object();
a.value = 1;
b = a;
b.value = 2;
alert(a.value);
Answer: 2 (examine the details of the cited data type)
12. The array var stringArray = ["This", "is", "Baidu", "Campus"] is known, and Alert outputs "This is Baidu Campus".
Answer: alert(stringArray.join(" "))
Then the problem is, there is known that the string foo="get-element-by-id", write a function to convert it into camel notation "getElementById".
function combo(msg){ var arr = msg.split("-"); var len = arr.length; //Storing arr.length in a local variable can improve the for loop efficiency for(var i=1;i<len;i++){ arr[i]=arr[i].charAt(0).toUpperCase()+arr[i].substr(1,arr[i].length-1); } msg=arr.join(""); return msg;}(Investigate the basic API)
13.var numberArray = [3,6,2,4,1,5]; (Investigate the basic API)
1) Implement the inverse order of this array and output [5,1,4,2,6,3]
2) Implement descending order arrangement of the array and output [6,5,4,3,2,1]
var numberArray = [3,6,2,4,1,5];numberArray.reverse(); // 5,1,4,2,6,3numberArray.sort(function(a,b){ //6,5,4,3,2,1 return ba; })14. Output today's date, in the form of YYYY-MM-DD. For example, today is September 26, 2014, then output 2014-09-26
var d = new Date();// Get the year, getFullYear() returns a 4-digit number var year = d.getFullYear();// Get the month, the month is quite special, 0 is January, and 11 is December var month = d.getMonth() + 1;// Become two-digit month = month < 10 ? '0' + month : month;// Get the day var day = d.getDate();day = day < 10 ? '0' + day : day;alert(year + '-' + month + '-' + day);
15. Replace {$id} in the string "<tr><td>{$id}</td><td>{$name}</td></tr>" with 10, and {$name} with Tony (using regular expressions)
Answer: "<tr><td>{$id}</td><td>{$id}_{$name}</td></tr>".replace(/{/$id}/g, '10').replace(/{/$name}/g, 'Tony');
16. In order to ensure the safety of page output, we often need to escape some special characters. Please write a function escapeHtml and escape <, >, &, "
function escapeHtml(str) {return str.replace(/[<>"&]/g, function(match) { switch (match) { case "<": return "<"; case ">": return ">"; case "&": return "&"; case "/": return ""; } });}17.foo = foo||bar , what does this line of code mean? Why do I write this way?
Answer: if(!foo) foo = bar; //If foo exists, the value remains unchanged, otherwise the value of bar is assigned to foo.
Short-circuit expression: As operand expressions of the "&&" and "||" operators, when these expressions are evaluated, the evaluation process will terminate as long as the final result can be determined to be true or false. This is called short-circuit evaluation.
18. Looking at the following code, what will be output? (Variable declaration enhancement)
The code copy is as follows:
var foo = 1;
function(){
console.log(foo);
var foo = 2;
console.log(foo);
}
Answer: Output undefined and 2. The above code is equivalent to:
var foo = 1;function(){ var foo; console.log(foo); //undefined foo = 2; console.log(foo); // 2; }Function declarations and variable declarations are implicitly promoted to the top of the current scope by the JavaScript engine, but only promoting the name does not promote the assignment part.
19. Use js to randomly select 10 numbers between 10 and 100, store them into an array, and sort them.
var iArray = []; function getRandom(start, iend){ var iChoice = isstart - iend +1; return Math.floor(Math.random() * iChoice + isstart;}for(var i=0; i<10; i++){ iArray.push(getRandom(10,100));}iArray.sort();20. Combine the two numbers and delete the second element.
The code copy is as follows:
var array1 = ['a','b','c'];
var bArray = ['d','e','f'];
var cArray = array1.concat(bArray);
cArray.splice(1,1);
21. How to add, remove, move, copy, create and find nodes (native JS, real basics, no detailed writing of every step)
1) Create a new node
createDocumentFragment() //Create a DOM fragment
createElement() //Create a specific element
createTextNode() //Create a text node
2) Add, remove, replace, insert
appendChild() //Add
removeChild() //Remove
replaceChild() //Replace
insertBefore() //Insert
3) Search
getElementsByTagName() //By tag name
getElementsByName() //The value of the Name property of the element is passed
getElementById() //Through element Id, uniqueness
22. There is such a URL: http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e. Please write a JS program to extract each GET parameter in the URL (the parameter name and number of parameters are uncertain), and return it to a json structure in the form of a key-value, such as {a:'1', b:'2', c:'', d:'xxx', e:undefined}.
Answer:
function serilizeUrl(url) { var result = {}; url = url.split("?")[1]; var map = url.split("&"); for(var i = 0, len = map.length; i < len; i++) { result[map[i].split("=")[0]] = map[i].split("=")[1]; } return result;}23. What is the difference between the regular expression constructor var reg=new RegExp("xxx") and the regular expression literal var reg=//? Regular expression matching mailbox?
Answer: When using the RegExp() constructor, not only do you need to escape quotes (i.e. /" means"), but you also need to also double backslash (i.e. // means a /). Using regular expression literals is more efficient.
Regular matching of email:
The code copy is as follows: var regMail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/;
24. Look at the following code and give the output result.
The code copy is as follows:
for(var i=1;i<=3;i++){
setTimeout(function(){
console.log(i);
},0);
};
Answer: 4 4 4.
Cause: The Javascript event processor will not run until the thread is idle. So the question is, how to make the above code output 1 2 3?
for(var i=1;i<=3;i++){ setTimeout((function(a){ //Instantly execute the function console.log(a); })(i),0); };1 //Output 2325. Write a function to clear the spaces before and after the string. (Compatible with all browsers)
Use the built-in interface trim(), considering compatibility:
if (!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^/s+/, "").replace(//s+$/,""); } } // test the function var str = " /t/n test string ".trim(); alert(str == "test string"); // alerts "true"26. What are the roles of callee and caller in Javascript?
Answer:
Caller returns a reference to the function that calls the current function;
callee returns the function function being executed, that is, the body of the specified function object.
So the question is? If a pair of rabbits give birth to a pair of rabbits every month; a pair of new rabbits will give birth to rabbits from the second month; assuming that each pair of rabbits is one female and one male, how many pairs of rabbits can a pair of rabbits breed into in the n month? (Use callee to complete)
var result=[];function fn(n){ //The typical Fibonacci sequence if(n==1){ return 1; }else if(n==2){ return 1; }else{ if(result[n]){ return result[n]; }else{ //argument.callee() means fn() result[n]=arguments.callee(n-1)+arguments.callee(n-2); return result[n]; } }}Intermediate Javascript:
1. Implement a function clone that can copy the 5 main data types in JavaScript (including Number, String, Object, Array, Boolean)
•Search Point 1: Is it clear whether the difference between the basic data type and the reference data type is stored in memory?
•Search Point 2: Do you know how to determine what type of a variable is?
•Inspection point 3: Design of recursive algorithm
// Method 1: Object.prototype.clone = function(){ var o = this.constructor === Array ? [] : {}; for(var e in this){ o[e] = typeof this[e] === "object" ? this[e].clone() : this[e]; } return o;}//Method 2: /** *Clone an object* @param Obj * @returns */ function clone(Obj) { var buf; if (Obj instanceof Array) { buf = []; //Create an empty array var i = Obj.length; while (i--) { buf[i] = clone(Obj[i]); } return buf; }else if (Obj instanceof Object){ buf = {}; //Create an empty object for (var k in Obj) { //Add a new attribute to this object buf[k] = clone(Obj[k]); } return buf; }else{ //Ordinary variables directly assign return Obj; } }2. How to eliminate duplicate elements in an array?
var arr=[1,2,3,3,4,4,5,5,6,1,9,3,25,4]; function deRepeat(){ var newArr=[]; var obj={}; var index=0; var l=arr.length; for(var i=0;i<l;i++){ if(obj[arr[i]]==undefined) { obj[arr[i]]=1; newArr[index++]=arr[i]; } else if(obj[arr[i]]==1) continue; } return newArr; } var newArr2=deRepeat(arr); alert(newArr2); //Output 1,2,3,4,5,6,9,253. Xiaoxian is a cute puppy (Dog), and its screams are very nice. Every time he sees his owner, he will scream (yelp). From this description, you can get the following objects:
function Dog() { this.wow = function() { alert('Wow'); } this.yelp = function() { this.wow(); }}Like Xiaoxian, Xiaomang turned out to be a cute puppy, but suddenly one day he went crazy (MadDog), and when he saw someone, he would scream (wow) and kept calling (yelp) every half a second. Please use code to implement it according to the description. (Inheritance, prototype, setInterval)
Answer:
function MadDog() { this.yelp = function() { var self = this; setInterval(function() { self.wow(); }, 500); }}MadDog.prototype = new Dog(); //for testvar dog = new Dog();dog.yelp();var madDog = new MadDog();madDog.yelp();4. The following ul, how to alert its index when clicking on each column? (closure)
The code copy is as follows:
<ul id=”test”>
<li>This is the first</li>
<li>This is the second</li>
<li>This is the third item</li>
</ul>
Answer:
// Method 1: var lis=document.getElementById('2223').getElementsByTagName('li');for(var i=0;i<3;i++){ lis[i].index=i; lis[i].onclick=function(){ alert(this.index); };}// Method 2: var lis=document.getElementById('2223').getElementsByTagName('li');for(var i=0;i<3;i++){ lis[i].index=i; lis[i].onclick=(function(a){ return function() { alert(a); } })(i);}5. Write a JavaScript function and enter a selector of the specified type (only three simple CSS selectors: id, class, and tagName, and no compatible combination selectors are required) to return matching DOM nodes, which need to consider browser compatibility and performance.
/*** @param selector {String} The incoming CSS selector. * @return {Array}*/
Answer: (too long, click to open)
var query = function(selector) { var reg = /^(#)?(/.)?(/w+)$/img; var regResult = reg.exec(selector); var result = []; //If it is an id selector if(regResult[1]) { if(regResult[3]) { if(typeof document.querySelector === "function") { result.push(document.querySelector(regResult[3])); } else { result.push(document.getElementById(regResult[3])); } } } //If it is a class selector else if(regResult[2]) { if(regResult[3]) { if(typeof document.getElementsByClassName === 'function') { var doms = document.getElementsByClassName(regResult[3]); if(doms) { result = converToArray(doms); } } //If the getElementsByClassName function is not supported else { var allDoms = document.getElementsByTagName("*") ; for(var i = 0, len = allDoms.length; i < len; i++) { if(allDoms[i].className.search(new RegExp(regResult[2])) > -1) { result.push(allDoms[i]); } } } } } } } //If it is a tag selector else if(regResult[3]) { var doms = document.getElementsByTagName(regResult[3].toLowerCase()); if(doms) { result = convertToArray(doms); } } return result; } function convertToArray(nodes){ var array = null; try{ array = Array.prototype.slice.call(nodes,0);//For non-IE browsers}catch(ex){ array = new Array(); for( var i = 0 ,len = nodes.length; i < len ; i++ ) { array.push(nodes[i]) } } return array; }6. Please evaluate the following code and give suggestions for improvement.
if(window.addEventListener){ var addListener = function(el,type,listener,useCapture){ el.addEventListener(type,listener,useCapture); };}else if(document.all){ addListener = function(el,type,listener){ el.attachEvent("on"+type,function(){ listener.apply(el); }); } }evaluate:
•The addListener function should not be declared in the if and else statements, it should be declared first;
•No need to use window.addEventListener or document.all to detect the browser, capability detection should be used;
• Since attachEvent has this pointing problem in IE, it needs to be handled when calling it
Improvements are as follows:
function addEvent(elem, type, handler){ if(elem.addEventListener){ elem.addEventListener(type, handler, false); }else if(elem.attachEvent){ elem['temp' + type + handler] = handler; elem[type + handler] = function(){ elem['temp' + type + handler].apply(elem); }; elem.attachEvent('on' + type, elem[type + handler]); }else{ elem['on' + type] = handler; }}7. Add a method to the String object, pass in a string type parameter, and then return the price space between each character of the string, for example:
addSpace("hello world") // -> 'helloworld d'
The code copy is as follows:
String.prototype.spacify = function(){
return this.split('').join(' ');
};
Then answer the above questions, then the question is
1) Is it safe to add methods directly to the object's prototype? Especially on Object objects. (I can't answer this? I hope I'll tell you what I know.)
2) What is the difference between function declaration and function expression?
Answer: In Javascript, when the parser loads data into the execution environment, it does not treat function declarations and function expressions equally. The parser will be the first to read the function declarations and make them available (accessible) before executing any code. As for the function expression, you must wait until the parser executes to the line of code where it is located before it will be parsed and executed. (Function declaration promotion)
8. Define a log method so that it can proxy console.log methods.
A feasible method:
The code copy is as follows:
function log(msg) {
console.log(msg);
}
log("hello world!") // hello world!
What if you want to pass multiple parameters? Obviously the above method cannot meet the requirements, so a better method is:
The code copy is as follows:
function log(){
console.log.apply(console, arguments);
};
So the question is, what are the similarities and differences between apply and call methods?
Answer:
The two functions of apply and call are the same, that is, calling one method of an object and replacing the current object with another object. Changes the object context of a function from the initial context to the new object specified by thisObj.
But there is a difference in parameters between the two. The meaning of the first parameter is the same, but for the second parameter: apply is passed in an array of parameters, that is, combining multiple parameters into an array, and the call is passed in as a parameter of the call (starting from the second parameter). For example, the corresponding apply writing method for func.call(func1,var1,var2,var3) is: func.apply(func1,[var1,var2,var3]).
9.What is a pseudo-array in Javascript? How to convert a pseudo-array into a standard array?
Answer:
Pseudo-array (class array): You cannot call array methods directly or expect any special behavior of length attributes, but you can still traverse them on real array traversal methods. Typically, the argument parameters of the function are also called getElementsByTagName, document.childNodes, etc., and they all return NodeList objects that belong to pseudo-arrays. Arrays can be converted into real Array objects using Array.prototype.slice.call(fakeArray).
Suppose we follow the eighth question stem, we need to add a "(app)" prefix to each log method, such as 'hello world!' ->'(app)hello world!'. The method is as follows:
function log(){ var args = Array.prototype.slice.call(arguments); //In order to use the unshift array method, convert argument into real array args.unshift('(app)'); console.log.apply(console, args); };10. For understanding the scope context and this, see the following code:
var User = { count: 1, getCount: function() { return this.count; }};console.log(User.getCount()); // what?var func = User.getCount;console.log(func()); // what?What are the outputs of two consoles? Why?
The answer is 1 and undefined.
func is executed in the context of winodw, so the count property cannot be accessed.
Then the question is, how to make sure Uesr can always access the context of func, that is, return 1 correctly.
Answer: The correct way is to use Function.prototype.bind. Compatible with each browser's complete code is as follows:
Function.prototype.bind = Function.prototype.bind || function(context){ var self = this; return function(){ return self.apply(context, arguments); };}var func = User.getCount.bind(User);console.log(func());11. What is the difference between native JS's window.onload and Jquery's $(document).ready(function(){})? How to implement Jq's ready method using native JS?
The window.onload() method must wait until all elements including the image in the page are loaded before execution.
$(document).ready() is executed after the DOM structure is drawn, and there is no need to wait until it is loaded.
/* * Pass the function to whenReady() * When the document is parsed and ready for the operation, the function is called as the method of the document */var whenReady = (function() { //This function returns whenReady() function var funcs = []; // When the event is obtained, the function to be run var ready = false; // When the event handler is triggered, switch to true // When the document is ready, call the event handler function handler(e) { if(ready) return; // Ensure that the event handler only runs completely once// If the onreadystatechange event occurs, but its state is not complete, then the document is not ready yet if(e.type === 'onreadystatechange' && document.readyState !== 'complete') { return; } //Run all registered functions//Be careful to calculate funcs.length every time //In case the call of these functions may cause more functions to be registered for(var i=0; i<funcs.length; i++) { funcs[i].call(document); } //The event handler is executed in full, switch the ready state, and remove all functions ready = true; funcs = null; } //Register the handler for any event received if(document.addEventListener) { document.addEventListener('DOMContentLoaded', handler, false); document.addEventListener('readystatechange', handler, false); //IE9+ window.addEventListener('load', handler, false); }else if(document.attachEvent) { document.attachEvent('onreadystatechange', handler); window.attachEvent('onload', handler); } //Return whenReady() function return function whenReady(fn) { if(ready) { fn.call(document); } else { funcs.push(fn); } }})();If the above code is very difficult to understand, the following simplified version:
function ready(fn){ if(document.addEventListener) { //Standard browser document.addEventListener('DOMContentLoaded', function() { //Login event to avoid repeated triggering of document.removeEventListener('DOMContentLoaded',arguments.callee, false); fn(); //Execute function}, false); }else if(document.attachEvent) { //IE document.attachEvent('onreadystatechange', function() { if(document.readyState == 'complete') { document.detachEvent('onreadystatechange', arguments.callee); fn(); //Function execution} }); }};12. (Design question) Want to implement a drag on a certain node of the page? How to do it? (Use native JS)
Just answer the concept, here are a few key points
1. Bind mousedown, mousemove, mouseup events to nodes that need to be dragged
2. After the mousedown event is triggered, start dragging and dragging
3. When mousemove, you need to obtain the drag position through event.clientX and clientY, and update the position in real time.
4. When mouseup, drag and drop ends
5. Pay attention to the browser boundaries
13.
function setcookie(name,value,days){ //Add a time variable to cookie var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); //Set the expiration time to days document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); } function getCookie(name){ var result = ""; var myCookie = ""+document.cookie+";"; var searchName = "+name+"="; var startOfCookie(name){ var result = ""; var myCookie = ""+document.cookie+";"; var searchName = "+name+"="; var startOfCookie = myCookie.indexOf(searchName); var endOfCookie; if(satrtOfCookie != -1){ startOfcookie += searchName.length; endOfCookie = myCookie.indexOf(";",startOfCookie); result = (myCookie.substring(startOfCookie,endOfCookie)); } return result;}(function(){ var oTips = document.getElementById('tips');//Suppose the id of tips is tips var page = { check: function(){//Check whether the tips' cookie exists and allow the display of var tips = getCookie('tips'); if(!tips || tips == 'show') return true;//The tips' cookie does not exist if(tips == "never_show_again") return false; }, hideTip: function(bNever){ if(bNever) setcookie('tips', 'never_show_again', 365); oTips.style.display = "none";//Hide}, showTip: function(){ oTips.style.display = "inline";//Show, assuming tips are row-level elements}, init: function(){ var _this = this; if(this.check()){ _this.showTip(); setcookie('tips', 'show', 1); } oTips.onclick = function(){ _this.hideTip(true); }; } }; page.init();})();14. Say what is the function of the following functions? What should be filled in the blank area?
//define (function(window){ function fn(str){ this.str=str; } fn.prototype.format = function(){ var arg = ______; return this.str.replace(_____,function(a,b){ return arg[b]||"; }); } window.fn = fn;})(window);//use(function(){ var t = new fn('<p><a href="{0}">{1}</a><span>{2}</span></p>'); console.log(t.format('http://www.alibaba.com','Alibaba','Welcome'));})();Answer: The purpose of accessing functions is to use the format function to replace the function's parameters like {0} and return a formatted result:
The first empty is: arguments
The second empty is: //{(/d+)/}/ig
15. Use object-oriented Javascript to introduce yourself. (No answer, please try it yourself)
Answer: Object or Json is a good choice.
16. Explain the principle of implementing ajax by native Js.
The full name of Ajax is Asynchronous JavaScript and XML. Among them, Asynchronous means asynchronous, which is different from the synchronization method used in traditional web development.
The principle of Ajax is simply to use the XmlHttpRequest object to send asynchronous requests to the server, obtain data from the server, and then use javascript to operate the DOM to update the page.
XMLHttpRequest is the core mechanism of ajax. It was first introduced in IE5 and is a technology that supports asynchronous requests. Simply put, JavaScript can promptly make requests and process responses to the server without blocking the user. Achieve no refresh effect.
The properties of the XMLHttpRequest object are:
• onreadystatechang The event handler for the event triggered by each state change.
• responseText Returns the string form of data from the server process.
• responseXML DOM-compatible document data object returned from the server process.
• status numeric codes returned from the server, such as common 404 (not found) and 200 (ready)
• status Text String information accompanied by status code
• readyState object state value
• 0 (Uninitialized) The object has been established, but has not been initialized (the open method has not been called)
• 1 (Initialization) The object has been established and the send method has not been called yet
• 2 (Send data) The send method has been called, but the current status and http header are unknown
• 3 (Data transmission) Some data has been received, because the response and http headers are incomplete, an error will occur when a responseBody and responseText is obtained.
• 4 (Complete) The data is received, and the complete response data can be obtained through responseXml and responseText.
The following is a simple encapsulation of a function: (slightly long, click to open)
ajax({ url: "./TestXHR.aspx", //Request address type: "POST", //Request method data: { name: "super", age: 20 }, //Request parameter dataType: "json", success: function (response, xml) { // Code executed after successful placement}, fail: function (status) { // Code executed after failure placement} }); function ajax(options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.dataType = options.dataType || "json"; var params = formatParams(options.data); //Create - non-IE6 - Step 1 if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); } else { //IE6 and below browsers var xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //Receive - Step 3 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status >= 200 && status < 300) { options.success && options.success(xhr.responseText, xhr.responseXML); } else { options.fail && options.fail(status); } } } //Connect and send - Step 2 if (options.type == "GET") { xhr.open("GET", options.url + "?" + params, true); xhr.send(null); } else if (options.type == "POST") { xhr.open("POST", options.url, true); //Set the content type when submitting the form xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(params); } } //Format parameter function formatParams(data) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name])); } arr.push(("v=" + Math.random()).replace(".")); return arr.join("&"); }The above code roughly describes the ajax process, and the explanation is Googled by yourself. The question is not finished. Do you know what Jsonp and pjax are?
Answer:
Jsonp: (JSON with Padding) is a cross-domain request method. The main principle is to take advantage of the feature that script tags can be requested across domains. The src attribute sends the request to the server, the server returns the js code, the web page accepts the response, and then executes it directly. This is the same as the principle of referencing external files through script tags. JSONP consists of two parts: callback function and data. The callback function is generally controlled by the web page and sent to the server side as parameters. The server side spells the function and data into a string and returns.
pjax: pjax is a new technology based on ajax+history.pushState. This technology can change the content of a page without refresh and can change the URL of the page. (Keypoint: It can implement back functions that cannot be achieved by ajax) pjax is an encapsulation of ajax+pushState, and supports local storage, animation and other functions. Currently, it supports various versions such as jquery, qwrap, kissy, etc.
If you think the question is OK, please click on a recommendation, as the number of questions will continue to increase.
You may be interested in: 2014 front-end written test questions for BAT and major Internet companies--Html, Css
Let's post the part where I gave the answer. I have time to post the answers I haven't made. Regarding the questions in the article, if there are better solutions or errors, please let me know that it is a sin to mislead people’s children.
Original text: http://www.cnblogs.com/coco1s/p/4029708.html