表单提交问题,我如何在URL末尾获取ID值?

时间:2015-03-31 07:48:37

标签: javascript php jquery forms

我有以下代码,我想在点击按钮上提交我的表格,点击功能工作正常,但告诉我如何在URL的末尾分配“ID”的值,如下面的代码所示。

  <script type="text/javascript">
    $(document).ready(function() {
    $(".btn-success").click(function(){
    var ID = $(this).prev('.sendEmail').attr('id');
        alert(ID);
    });
    });
    </script>


    <script type="text/javascript">
    $(document).ready(function() {
      var form = $('#form2'); // contact form
      var submit = $('#submit2');  // submit button
      var alert = $('.alert'); // alert div for show alert message




      // form submit event
      form.on('submit', function(e) {
        e.preventDefault(); // prevent default form submit

        $.ajax({
          url: '//mydomain.com/'+ID, 
          type: 'POST', // form submit method get/post
          dataType: 'html', // request type html/json/xml
          data: form.serialize(), // serialize form data 
          beforeSend: function() {
            alert.fadeOut();
            submit.html('Sending....'); // change submit button text
          },
          success: function(data) {
            alert.html(data).fadeIn(); // fade in response data
            form.trigger('reset'); // reset form
            submit.html('&#10004; Alert Successfully Sent!'); // reset submit button text
          },
          error: function(e) {
            console.log(e)
          }
        });
      });
    });
    </script>

1 个答案:

答案 0 :(得分:2)

您需要创建ID var global:

var ID;
$(document).ready(function() {
    $(".btn-success").click(function(){
        ID = $(this).prev('.sendEmail').attr('id');
        alert(ID);
    });
});

...其余的代码

或者,如果您合并文档就绪电话:

$(document).ready(function() {
    var ID;
    $(".btn-success").click(function(){
        ID = $(this).prev('.sendEmail').attr('id');
        alert(ID);
    });

   var form = $('#form2'); // contact form
   var submit = $('#submit2');  // submit button
   var alert = $('.alert'); // alert div for show alert message

   form.on('submit', function(e) {
    e.preventDefault(); // prevent default form submit

    $.ajax({
      url: '//mydomain.com/'+ID, 
      type: 'POST', // form submit method get/post
      dataType: 'html', // request type html/json/xml
      data: form.serialize(), // serialize form data 
      beforeSend: function() {
        alert.fadeOut();
        submit.html('Sending....'); // change submit button text
      },
      success: function(data) {
        alert.html(data).fadeIn(); // fade in response data
        form.trigger('reset'); // reset form
        submit.html('&#10004; Alert Successfully Sent!'); // reset submit button text
      },
      error: function(e) {
        console.log(e)
      }
    });
  });
});

This may help you understand more about variable scope