Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Prevención de la doble presentación de datos en formularios

Supongamos que tengo un área de texto en un formulario llamado urlslist donde el usuario ingresará una lista de URL, una en cada línea. Manejo el envío a través de ajax con consulta de la siguiente manera.

 $(function () { $("#urlslist").submit(function(e) { //prevent Default functionality e.preventDefault(); //get the action-url of the form var actionurl = e.currentTarget.action; //do your own request an handle the results $.ajax({ url: actionurl, type: 'post', dataType: 'json', data: $("#urlslist").serialize(), success: function(data) { //put the result in another textarea here } }); }); });

Luego muestro el resultado de mi procesamiento (es decir, otra URL para cada entrada) en otra área de texto. Funciona bien, pero quiero mejorarlo para que las URL antiguas no se envíen al servidor a través de ajax sin borrar ninguna de las áreas de texto.

Editar 1

Creo que necesito demostrar esto con un ejemplo.

Supongamos que el urlslist texto de la lista de URL contiene una URL. Hago clic en Enviar y obtengo un resultado. Ahora agrego otra URL en la lista de urlslist y hago clic en Enviar nuevamente. Ahora habrá 2 URL en la solicitud de publicación. ¿Cómo puedo asegurarme de que solo se envían nuevas urls.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Usando la librería Hacer algo solo una vez de Mozilla:

 function executeOnce() { var argc = arguments.length, bImplGlob = typeof arguments[argc - 1] === "string"; if (bImplGlob) { argc++; } if (argc < 3) { throw new TypeError("executeOnce - not enough arguments"); } var fExec = arguments[0], sKey = arguments[argc - 2]; if (typeof fExec !== "function") { throw new TypeError("executeOnce - first argument must be a function"); } if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { throw new TypeError("executeOnce - invalid identifier"); } if (decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) === "1") { return false; } fExec.apply(argc > 3 ? arguments[1] : null, argc > 4 ? Array.prototype.slice.call(arguments, 2, argc - 2) : []); document.cookie = encodeURIComponent(sKey) + "=1; expires=Fri, 31 Dec 9999 23:59:59 GMT" + (bImplGlob || !arguments[argc - 1] ? "; path=/" : ""); return true; }

Puedes hacer lo siguiente:

 // some custom helper String.prototype.s2b64 = function() { // make base64 from string return window.btoa(unescape(encodeURIComponent(this))); } String.prototype.replaceArray = function(find, replace) { // replace by array var replaceString = this; for (var i = 0; i < find.length; i++) { replaceString = replaceString.replace(find[i], replace[i]); } return replaceString; }; // here we start : var output = []; $.each($("#urlslist textarea").first().val().split(/\n/), function(index, value) { alert(index + ": " + value); if (value != '') executeOnce(function(v) { output.push(value); }, null, value, 'urldone_' + value.s2b64().replaceArray( ["expires", "path", "domain", "secure"], ["e_xpires", "p_ath", "d_omain", "s_ecure"]) + ''); }); alert(output);

Algunas partes pueden parecer un poco extrañas, pero se trata de probar el setCookie manual (como el uso de b64 y la búsqueda y reemplazo en caso de que tengamos mucha mala suerte y obtengamos aleatoriamente una palabra clave de cookie de la salida b64)

Y si desea eliminar todo el valor guardado, aquí está el código:

 var cookieNames = document.cookie.split(/=[^;]*(?:;\s*|$)/); // Remove any that match the pattern for (var i = 0; i < cookieNames.length; i++) { if (/^urldone_/.test(cookieNames[i])) { document.cookie = cookieNames[i] + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/'; } }

JSfiddle

Esta es una respuesta basada en cookies (por navegador, prueba de actualización y reinicio).

about 4 years ago · Santiago Trujillo Report

0

Aquí hay un ejemplo de trabajo desarrollado a partir de este enlace http://jsfiddle.net/userdude/2hgnZ/

 $('form#id').submit(function(e){ var form = $(this); form.children('input[type=submit]').attr('disabled', 'disabled'); // this is just for demonstration e.preventDefault(); $.ajax({ url: ' http://fiddle.jshell.net/_display/', type: 'get', success: function(data) { alert(data); form.children('input[type=submit]').removeAttr('disabled'); } }); return false; });
about 4 years ago · Santiago Trujillo Report

0

 var map = [] map['www.google.com'] = 'www.google.com'; var urls = ['www.google.com', 'www.yahoo.com']; //this is form text area for (var i = 0; i< urls.length; i++) { if (map[urls[i]] !== urls[i]) { console.log('post ' +); map[urls[i]] = urls[i]; } else { console.log('don not post ' + urls[i]); } }

Lea el código de la consola anterior, es posible que tenga alguna idea Aquí lo guardo
paso 1) var mapa = [] global
paso 2) map['www.google.com'] = 'www.google.com'; esta línea demuestra ya publicada
paso 3) recorra las URL de var, que es su área de texto
paso 4) if (map[urls[i]] !== urls[i]) verifique el enlace actual ya publicado si no se publica, de lo contrario no se publica

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!