我的代碼有問題。我一直在試圖設計一個表單,可以更新數據庫中的數據並在不刷新頁面的情況下顯示它。我可以這樣做,但我希望如果用戶按下Enter鍵,表單就可以工作。 這裏是我的代碼:Ajax提交表單並輸入onclick
<form name="chat" id="chat">
<textarea name="message" type="text" id="message" size="63" ></textarea>
<input type="button" value="Send" onClick="send();"/>
</form>
<script>
//This function will display the messages
function showmessages(){
//Send an XMLHttpRequest to the 'show-message.php' file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","chat.php?jogo=<?php echo $numerojogo;?>",false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","chat.php",false);
xmlhttp.send();
}
//Replace the content of the messages with the response from the 'show-messages.php' file
document.getElementById('chatbox').innerHTML = xmlhttp.responseText;
//Repeat the function each 30 seconds
setTimeout('showmessages()',30000);
}
//Start the showmessages() function
showmessages();
//This function will submit the message
function send(){
//Send an XMLHttpRequest to the 'send.php' file with all the required informations~
var sendto = 'adicionar.php?message=' + document.getElementById('message').value + '&jogador=<?php echo $user;?>' + '&jogo=<?php echo $numerojogo;?>';
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",sendto,false);
xmlhttp.send(null);
document.getElementById("chat").reset();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",sendto,false);
xmlhttp.send();
}
var error = '';
//If an error occurs the 'send.php' file send`s the number of the error and based on that number a message is displayed
switch(parseInt(xmlhttp.responseText)){
case 1:
error = 'The database is down!';
break;
case 2:
error = 'The database is down!';
break;
case 3:
error = 'Don`t forget the message!';
break;
case 4:
error = 'The message is too long!';
break;
case 5:
error = 'Don`t forget the name!';
break;
case 6:
error = 'The name is too long!';
break;
case 7:
error = 'This name is already used by somebody else!';
break;
case 8:
error = 'The database is down!';
}
if(error == ''){
$('input[type=text]').attr('value', '');
showmessages();
}
else{
document.getElementById('error').innerHTML = error;
}
}
</script>
我試圖把的onsubmit代替的onclick但沒有成功:/
編輯: 已經解決了我很愚蠢的。謝謝你的幫助MISKO ! 這裏是我的代碼,如果你遇到同樣的麻煩是我:
<form name="chat" id="chat" onsubmit="send();return false;">
<input name="message" type="text" id="message" size="63" ></input>
<input type="button" value="Send" onClick="send();"/>
</form>
只是釘了它,非常感謝你!我不得不添加返回false,但它工作得很好! – 2014-11-08 21:10:05
你是對的,你必須返回false,所以表單不會真的提交,但只在裏面執行帶有AJAX請求的* send()*方法。 – misko321 2014-11-08 21:20:40