English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Generalmente, cuando escribimos páginas web y utilizamos solicitudes Ajax para el servidor, usamos bibliotecas ya encapsuladas como JQuery, lo que es bastante simple.
Pero generalmente, estas bibliotecas tienen muchas funciones, introduciendo muchas cosas que no necesitamos. Si necesitamos escribir una página web simple y funcional, no es necesario referirse a archivos de bibliotecas tan grandes.
Podemos implementar una función de solicitud Ajax propia de manera sencilla, el código específico es el siguiente:
var ajax = {}; ajax.x = function () { if (typeof XMLHttpRequest !== 'undefined') { return new XMLHttpRequest(); } var versions = [ "MSXML2.XmlHttp.6.0", "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ]; var xhr; for (var i = 0; i < versions.length; i++) { try { xhr = new ActiveXObject(versions[i]); break; } catch (e) { } } return xhr; }; ajax.send = function (url, method, data, success,fail,async) { if (async === undefined) { async = true; } var x = ajax.x(); x.open(method, url, async); x.onreadystatechange = function () { if (x.readyState == 4) { var status = x.status; if (status >= 200 && status < 300) { success && success(x.responseText,x.responseXML) } else { fail && fail(status); } } }; if (method == 'POST') { x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } x.send(data) }; ajax.get = function (url, data, callback, fail, async) { var query = []; for (var key in data) { query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } ajax.send(url + (query.length ? '? + query.join('&') : ''), 'GET', null, callback, fail, async) }; ajax.post = function (url, data, callback, fail, async) { var query = []; for (var key in data) { query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } ajax.send(url,'POST', query.join('&'), callback, fail, async) };
Método de uso: GET
ajax.get('/test.php', {foo: 'bar'}, function(response,xml) { //success }, function(status){ //fail }); POST ajax.post('/test.php', {foo: 'bar'}, function(response,xml) { //succcess },function(status){ //fail });
Es necesario prestar atención a un problema aquí, si queremos enviar algo similar a
var sendCmd = "?op_code=" + code + "&op_cmd=" + cmd; ajax.post('/control + sendCmd,'',function(response,xml) { console.log('success'); }, function(status){ console.log('failed:'); + status); });
Resumen
El resumen anterior es la función del solicitante de Ajax en JavaScript nativo que presento al editor. Espero que sea útil para todos. Si tienes alguna pregunta, déjame un mensaje y responderé a tiempo. También agradezco mucho el apoyo a la guía de gritos!
Declaración: El contenido de este artículo se obtiene de la red, es propiedad del autor original, se carga de manera autónoma por los usuarios de Internet y este sitio no posee los derechos de propiedad, no se ha procesado editorialmente y no asume ninguna responsabilidad legal. Si encuentra contenido sospechoso de infracción de derechos de autor, por favor envíe un correo electrónico a: notice#w.3Aviso: Si encuentra contenido infractor, envíe un correo electrónico a notice#w con el # reemplazado por @ y proporcione evidencia relevante. Una vez verificada, este sitio eliminará inmediatamente el contenido sospechoso de infracción.