2012-04-07 123 views
1

我想使用jQuery提交不使用頁面刷新的表單。我發現了一些在線的例子,像這樣的: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/使用jQuery提交不使用頁面刷新的表單

,但問題是他們有硬編碼的表單字段:

<div id="contact_form"> 
    <form name="contact" action=""> 
    <fieldset> 
     <label for="name" id="name_label">Name</label> 
     <input type="text" name="name" id="name" size="30" value="" class="text-input" /> 
     <label class="error" for="name" id="name_error">This field is required.</label> 

     <label for="email" id="email_label">Return Email</label> 
     <input type="text" name="email" id="email" size="30" value="" class="text-input" /> 
     <label class="error" for="email" id="email_error">This field is required.</label> 

     <label for="phone" id="phone_label">Return Phone</label> 
     <input type="text" name="phone" id="phone" size="30" value="" class="text-input" /> 
     <label class="error" for="phone" id="phone_error">This field is required.</label> 

     <br /> 
     <input type="submit" name="submit" class="button" id="submit_btn" value="Send" /> 
    </fieldset> 
    </form> 
    </div> 

和JavaScript:

var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone; 
    //alert (dataString);return false; 
    $.ajax({ 
    type: "POST", 
    url: "bin/process.php", 
    data: dataString, 
    success: function() { 
     $('#contact_form').html("<div id='message'></div>"); 
     $('#message').html("<h2>Contact Form Submitted!</h2>") 
     .append("<p>We will be in touch soon.</p>") 
     .hide() 
     .fadeIn(1500, function() { 
     $('#message').append("<img id='checkmark' src='images/check.png' />"); 
     }); 
    } 
    }); 
    return false; 

在例子中以上,dataString是從硬編碼的表單字段創建的。我的表單是動態的,所以我不知道它的輸入字段的名稱。

注意:雖然表單字段是動態的,但表單名稱是硬編碼的,所以我猜想一個選項是通過子節點並解析值。但我想知道是否有更簡單的方法。

回答

5

data: $("#contact_form form").serializeArray()應該這樣做。

+0

爲什麼'serializeArray()'?示例代碼使用一個字符串,這正是'.serialize()'的用途。 – 2012-04-07 19:58:01

+0

完美的作品,謝謝。 15分鐘限制結束後,我會接受答案。 – Caner 2012-04-07 19:59:01

+0

@AonyonyGrist個人喜好。結果是一樣的。 – 2012-04-07 19:59:02

1

卡納,我害怕,因爲你的表格是動態的,並不是一個簡單的方法。你需要使用像這樣的代碼通過表單去:

var message = ""; 
$("#formID input").each(function() { 
    message += $(this).attr("name"); 
}); 

這樣的代碼,將得到每一個表單輸入的名稱,並將其串聯到一個名爲消息字符串。在這種情況下,您可以比我更具體,但您應該瞭解基本想法並使用此代碼來滿足您的需求。

+0

幸好它似乎有另一種方式,看到其他答案 – Caner 2012-04-07 20:02:45

+0

太棒了!很高興聽到你找到了更好的解決方案,對不起,我不是你正在尋找什麼。 – cereallarceny 2012-04-07 20:03:48