js多线程
js代码
1 var Ajax={ 2 get: function(url, func) { 3 var obj = new XMLHttpRequest(); 4 obj.open('GET', url, false); 5 obj.onreadystatechange = function() { 6 if (obj.readyState == 4 && obj.status == 200 || obj.status == 304) { 7 func(this, obj.responseText); 8 postMessage(obj.responseText); 9 } 10 }; 11 obj.send(); 12 }, 13 post: function (url, data, func) { 14 var obj = new XMLHttpRequest(); 15 obj.open("POST", url, true); 16 obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 17 obj.onreadystatechange = function() { 18 if (obj.readyState == 4 && (obj.status == 200 || obj.status == 304)) { 19 func.call(this, obj.responseText); 20 } 21 }; 22 obj.send(data); 23 } 24 }; 25 var url = "https://********"; 26 var yourFn = function(ele,val){ 27 console.log(val); 28 }; 29 Ajax.get(url, yourFn);
html代码
<!DOCTYPE html> <head> <title>test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script src="jquery-1.4.4.min.js"></script> <script> function init(){ var workers = new Worker('http://localhost:8080/bendi.js'); workers.onmessage = function(event){ alert(event.data); }; alert(1); }; </script> </head> <body onload = "init()"> </body> </html>
运行的话,ajax 这个本来就是异步的,所以是先执行alert(1);然后弹出请求的数据。