2012-03-17 29 views
12

¿cuál es la forma más fácil de convertir una cadena GET URL a POST en jQuery?JQuery: Convertir GET URL en POST

p. Ej. Quiero los parámetros de un enlace

<a href="/somepage?x=1&amp;y=3" id="postlink">link</a> 

que se enviarán como POST onclick si JavaScript está activado. No AJAX, solo presentación de formulario normal.

alguna idea?

Gracias, Hannes.

+0

ser específico acerca de sus necesidades .. no puede averiguar cuál es su prooblem ?? –

+0

encontró que esto podría ser útil http://tomengineering.tripod.com/gettopost.html – elclanrs

+0

El "problema" es que quiero que los datos solo se envíen a través de POST si Javascript está activado. Me imagino que podría agregar un formulario oculto basado en la URL al DOM sobre la marcha. Pero, ¿hay una manera más fácil o más elegante? – ottsch

Respuesta

12

acabo de escribir este código, compruebe por favor, puede ser útil http://jsfiddle.net/AEwxt/

$('#postlink').click(function() { 
    var p = $(this).attr('href').split('?'); 
    var action = p[0]; 
    var params = p[1].split('&'); 
    var form = $(document.createElement('form')).attr('action', action).attr('method','post'); 
    $('body').append(form); 
    for (var i in params) { 
     var tmp= params[i].split('='); 
     var key = tmp[0], value = tmp[1]; 
     $(document.createElement('input')).attr('type', 'hidden').attr('name', key).attr('value', value).appendTo(form); 
    } 
    $(form).submit(); 
    return false; 
}); 
+0

Gracias, eso es lo que estaba buscando. – ottsch

+1

Solo se necesita agregar .attr ('método', 'publicación): http://jsfiddle.net/xcpMk/ – ottsch

+0

¿Por qué repite ".attr (' tipo ',' oculto '). Attr (' nombre ', clave) .attr ('valor', valor) "? Esto desencadena un error IE8 en jQuery y parece ser un error tipográfico :) – AlfaTeK

-1

Puede enviar entrada de un formulario utilizando HTML método < forma = "POST">

Aunque no estoy completamente seguro de la razón detrás de esto, si debe aplicar la parte de JavaScript, simplemente rodear el formulario con < forma method = "GET"> con una etiqueta < noscript>.

3

demo: http://jsfiddle.net/w5WA6/

function getUrlVars(_url) 
{ 
    var vars = [], hash; 
    var hashes = _url.slice(_url.indexOf('?') + 1).split('&'); 

    for(var i = 0; i < hashes.length; i++) 
    { 
     hash = hashes[i].split('='); 
     vars.push(hash[0]); 
     vars[hash[0]] = hash[1]; 

    } 

    return vars; 
} 

var arVars = getUrlVars($("#test").attr("href")); 
for(var i=0;i<arVars.length;i++){ 
    //put var in input for submition you can change type by `hidden` 
    $("#myForm").append("<input type='text' value='"+arVars[arVars[i]]+"' name='"+arVars[i]+"'/>"); 
} 
​ 
2

Modificado código de Sergey un poco, de modo que cuando el usuario se sitúa 'en el enlace, que no muestra la solicitud GET.

Enlace:

<a href="#" postURL="/tpl/schRosterSearchSubmit.do?searchReci.uniqueId=&searchReci.studentId=&searchReci.schoolId=3205&searchReci.name.firstName=&searchReci.name.lastName=&searchReci.gender=&searchReci.rdobDay=&searchReci.rdobMonth=&searchReci.rdobYear=&searchReci.rssn1=&searchReci.rssn2=&searchReci.rssn3=&searchReci.phoneNumber=&searchReci.citzOrResAlien=&searchReci.country.isoCountryCode=&searchReci.address.street1=&searchReci.address.street2=&searchReci.address.city=&searchReci.address.state=&searchReci.address.zip=&searchReci.address.zipExt=&searchReci.parentN.firstName=&searchReci.parentN.lastName=&searchReci.parentEmail=&searchReci.parentMAddr.street1=&searchReci.parentMAddr.street2=&searchReci.parentMAddr.city=&searchReci.parentMAddr.state=&searchReci.parentMAddr.zip=&searchReci.parentMAddr.zipExt=&searchReci.parentPAddr.street1=&searchReci.parentPAddr.street2=&searchReci.parentPAddr.city=&searchReci.parentPAddr.state=&searchReci.parentPAddr.zip=&searchReci.parentPAddr.zipExt=&searchReci.pdobDay=&searchReci.pdobMonth=&searchReci.pdobYear=&searchReci.pssn1=&searchReci.pssn2=&searchReci.pssn3=&searchReci.parentCitzOrResAlien=&searchReci.parentCountry.isoCountryCode=&searchReci.addrUpdInd=&searchReci.inactiveDtDay=&searchReci.inactiveDtMonth=&searchReci.inactiveDtYear=&searchReci.ncoaUpdInd=&searchReci.badAddrInd=&branding=upromise&acct=XXXX&schRosterPager.offset=50" class="rnavLink">2nd Page results</a> 

la conversión a POST onclick:

<script type="text/javascript"> 
$(document).ready(function() { 
    $('.rnavLink').click(function() { 
     var p = $(this).attr('postURL').split('?'); 
     var action = p[0]; 
     var params = p[1].split('&'); 
     var form = $('<form/>', {action:action, method:'post'}).appendTo('body'); 
     for (var i in params) { 
      var tmp = params[i].split('='); 
      var key = tmp[0], value = tmp[1]; 
      $('<input/>', {type:'hidden', name:key, value:value}).appendTo(form); 
     } 
     $(form).submit(); 
     return false; 
    }); 
});