ajax從後臺請求的數據在顯示時一閃而過的緣由(submit)

學習過程當中遇到的問題:php

先貼代碼:html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行的代碼
 xmlhttp=new XMLHttpRequest(); } else { //IE6, IE5 瀏覽器執行的代碼
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_post.php?q="+str,true); xmlhttp.send(); } </script>
</head>
<body>

<p><b>在輸入框中輸入一個姓名:</b></p>
<form> 姓名: <input type="text" id="text" />
<input type="submit" onclick="showHint(text.value)" />
</form>
<p>返回值: <span id="txtHint"></span></p>

</body>
</html>

向後臺發送文本框中的數據,後臺返回結果顯示在頁面上,可是會發現顯示結果會一閃而過。ajax

能顯示出來結果說明請求已經成功了瀏覽器

可是一閃而過的緣由是什麼?函數

通過多方尋找post

終於學習

發現spa

code

submitorm

的緣由

.......

解決辦法以下:

1. 將submit換成button

2. 在函數後面添加 return false;即<input type="submit" onclick="showHint(text.value); return false" />

解決完成

相關文章
相關標籤/搜索