使用ajax和jquery将type按钮转换为submit

converting type button to submit with ajax and jquery

本文关键字:按钮 转换 submit type ajax jquery 使用      更新时间:2023-09-26

问题:当我单击按钮type="button"时,它会显示所有数据。但如果我将其更改为type="submit",则不会显示数据。我想要的是将这个type="button"转换为type="submit",以显示数据。

这是我的代码:

<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 w/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 = "";
        }

您需要停止提交的正常执行。这是最后一个代码:

$("#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>

这应该能解决你的问题。