我構建的JS/Ajax函數沒有按鈕單擊或頁面刷新。該函數獲取輸入字段的值,並用php回顯結果。但每次變量都被回顯時,下一個變量會擦除前一個變量的值。如何避免這種情況? EXAMPLEPHP/JS:在不丟失值的情況下響應多個變量
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');
}
});
return false; }
$('#contact_name').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#contact_name").val();
dataString = 'name='+ name;
});
$('#email').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#email").val();
dataString = 'name='+ name;
});
$('#phone').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#phone").val();
dataString = 'name='+ name;
});
$('#address').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#address").val();
dataString = 'name='+ name;
});
$('#website').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#website").val();
dataString = 'name='+ name;
});
});
</script>
HTML/PHP
<form action="" method="post" enctype="multipart/form-data" id="contact_form" name="form4">
<div class="row">
<div class="label">Contact Name *</div> <!-- end .label -->
<div class="input">
<input type="text" id="contact_name" class="detail" name="contact_name" value="<?php $contact_name ?>" />
<div id="special"><span id="resultval"></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
<div class="row">
<div class="label">Email Address *</div> <!-- end .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php $email ?>" />
<div id="special"><span id="resultval"></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
</form>
謝謝!關於ID的一個問題:我如何使ID唯一? – CodingWonders90 2012-07-20 05:47:05
@cholomanCoding歡迎你,他們不應該是類似的,例如你有兩個id爲'#special'的元素,你可以把它們改成'#special1'和'#special2',或者簡單地使用一個類如'.special '。 – undefined 2012-07-20 05:49:38
噢,好的。因此,如果我將div更改爲'
'和'',我還需要添加:$('#special1')。append(''+ result +'
');' '$(' (''#special2')。append(''+ result +'
');' – CodingWonders90 2012-07-20 06:05:09