2016-01-08 17 views
1

問題:當我點擊按鈕類型=「按鈕」它顯示所有數據。但如果我將其更改爲type =「submit」,它不會顯示數據。我想要的是將此類型=「按鈕」轉換爲可顯示數據的type =「submit」。轉換類型按鈕提交與Ajax和jQuery

這裏是我的代碼:

<form name="chatform"> 
           <div class="input-group" id="msg"> 
            <input type="text" class="form-control" name="inputmsg" placeholder="Enter message here. . ." id="inputmsg"> 
            <span class="input-group-btn"> 
             <button class="btn btn-success" type="button" name="btn-send" id="cnd" onClick="submitChat()">Send</button> 
            </span> 
           </div> 
          </form> 

AJAX瓦特/ jQuery的

function submitChat(){ 
      if(chatform.inputmsg.value== ""){ 
       alert("fill in blanks"); 
       return; 
       } 
       var msg = chatform.inputmsg.value; 
       var xhttp = new XMLHttpRequest(); 
       xhttp.onreadystatechange = function(){ 
       if(xhttp.readyState == 4 && xhttp.status==200){ 
        document.getElementById("chatlogs").innerHTML = xhttp.reponseText ? xhttp.reponseText : ""; 
       } 
       }; 
       xhttp.open("GET","insert.php?msg="+msg, true); 
       xhttp.send(); 
       $(document).ready(function(){ 
       $.ajaxSetup({cache:false}); 
       setInterval(function(){ 
        $("#chatlogs").load("logs.php"); 
       }, 2000); 
       }); 
       document.getElementById("inputmsg").value = ""; 
     } 
+2

嘗試更改'function submitChat()'到'function submitChat(e)'並在函數內部的第一行運行'e.preventDefault();' – Phiter

回答

2

你需要停止提交的正常執行。這是最後的代碼:

$("#inputmsg").keypress(function(e){ 
    if(e.which == 13){ 
     e.preventDefault(); 
     submitChat(); 
    } 
}); 

$("#cnd").click(function(e){ 
    e.preventDefault(); 
    submitChat(); 
}); 

function submitChat(){ 
    if(chatform.inputmsg.value== ""){ 
     alert("fill in blanks"); 
     return; 
    } 
    var msg = chatform.inputmsg.value; 
    var xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function(){ 
     if(xhttp.readyState == 4 && xhttp.status==200){ 
      document.getElementById("chatlogs").innerHTML = xhttp.reponseText ? xhttp.reponseText : ""; 
     } 
    }; 
    xhttp.open("GET","insert.php?msg="+msg, true); 
    xhttp.send(); 
    $(document).ready(function(){ 
     $.ajaxSetup({cache:false}); 
     setInterval(function(){ 
      $("#chatlogs").load("logs.php"); 
     }, 2000); 
    }); 
    document.getElementById("inputmsg").value = ""; 
} 

然後在HTML按鈕刪除點擊功能:

<button class="btn btn-success" type="button" name="btn-send" id="cnd">Send</button> 

這應該解決您的問題。

+0

哇!就像我在評論中所說的那樣! – Phiter

+0

@PhiterFernandes對不起!我沒有看到您的評論! :-( – erikscandola

+0

在那些你不知道究竟是什麼可能導致行爲的情況下,你必須在發佈可能不是正確的答案之前發表評論,即使在這種情況下你的答案是正確的。 – Phiter