Get url variables from url to form with jquery

后端 未结 2 1446
死守一世寂寞
死守一世寂寞 2021-01-23 14:38

I have a html form which only shows a price, but don\'t submit anything to the server. This works fine now.

How can I add the function of running this form just from url

2条回答
  •  臣服心动
    2021-01-23 15:21

    to fill input form URL

    function getURLParameter(name) {
      return decodeURI(
       (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
       );
    }
    var smoker = getURLParameter('smoker');
    var amount = getURLParameter('amount');
    var age = getURLParameter('age');
    
    $('#smoker').val( smoker );
    $('#amount').val( amount );
    if(age != 'null'){
        $('#age').val( age );
        calculAmount(obj);
    }
    
    //Find the value when form is submitted
    $('form').submit(function(e) {
        e.preventDefault();
        calculAmount(obj);
    });
    

    To send data to server, you can use get, post or ajax jquery

    Replace $('#calc').click(function(e) by $('form').submit(function(e)

    using get:

     //Empty the div
     $('#price-result').empty();
    
    $.get("www.my-domain.com/formurl/",
     { smoke: selectedSmoke , amount: amount ,age: selectedage} );
    

    or

    $.post('www.my-domain.com/formurl/', $("form").serialize(), function(data) {
      console.log("data sent");
    });
    

    or

    $.ajax({
             type : 'POST',
             url : 'www.my-domain.com/formurl/',
             data: $("form").serialize(),
             success : function(data){                                               
                       console.log("data sent");
              },
              error: function (request, status, error) {
                     console.log(request.responseText);
              } 
          });
    

提交回复
热议问题