使用锚标记提交表单而不刷新页面

时间:2016-01-24 09:15:21

标签: javascript html forms

我尝试使用basicModal在点击我的锚标记提交表单后进行模态弹出。我最初有一个按钮标签,但在我看来,basicModal只适用于锚标签,所以我切换到了。问题是当我通过单击按钮提交表单时,页面刷新而模块实际上没有弹出。话虽这么说,我希望我能够使用锚标签提交表单而不刷新页面,以便模式可以弹出。

我尝试过: <a class="alert button large" href="javascript:$('form').submit();" onclick="return false;">Submit!</a>

要提交表单,但不要点击return false,但这不起作用。

代码如下所示:

    <form method="POST" action="" class="form">
      <div class="small-6 small-centered columns">
          <select name="city">
            <option value="" disabled selected>Select a City</option>
            <option value="nyc">NYC</option>
            <option value="philly">Phladelphia</option>
            <option value="rot">Rotchester</option>
            <option value="sf">San Francisco</option>
            <option value="boston">Boston</option>
            <option value="la">Los Angeles</option>
          </select>
          <br/><br/>
          <select name="category">
            <option value="" disabled selected>Select a Category</option>
            <option value="cs">Computer Science</option>
            <option value="math">Mathematics</option>
            <option value="bio">Biology</option>
            <option value="chem">Chemistry</option>
            <option value="physics">Physics</option>
            <option value="art">Art</option>
            <option value="lang">Linguistics</option>
            <option value="astro">Astrology</option>
          </select>
          <br/><br/>
                <input type="text" class="span2" name="get-date" value="Select a Date" id="dp1">
          <br/><br/>
            <div class="btnn">
              <a class="alert button large" href="javascript:$('form').submit();" onclick="return false;">Submit!</a>
            </div>
          </div>
      </div>
    </form>

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要将表单提交到服务器,然后使用模式弹出窗口显示响应,而不刷新页面。然后你需要ajax请求:

var submitForm = function()
{
    $.ajax({
        type: 'post',
        url: '',
        data: $('form').serialize(),
        success: function(response){
            //open your modal here
        }
    })
}

和按钮:

<a class="alert button large" href="javascript:submitForm()">Submit!</a>

答案 1 :(得分:1)

考虑以下示例:

<a class="alert button large" href="javascript:void(0)" onclick="submitForm();">Submit!</a>
function submitForm(){
    $.ajax({
        type: 'POST',
        url: '<url>',  // change to your url
        data: $('.form').serialize(),
        success: function(response){
            basicModal.show({    // just for example
                body: '<p>This is a dead-simple alert modal!<br>The message can be filled with anything you want.</p>',
                buttons: {
                     action: {
                         title: 'Dismiss',
                         fn: basicModal.close
                     }
                }
            });
        }
    });
}