想为我的网站创建一个完全动态的聊天用户界面,但是如果有人提交按钮页面,它会重新加载整个页面,不应像许多聊天网站那样重新加载。
<form action="action.php" method="post" id="formpost">
<input type="text" id="input" value="php echo">
<input type="submit" value="send">
</form>
我想通过ajax提交这个表单并显示最后的xml <message>
包含 <message>talk 123<message>
<messages category="short">
<person1>
<time>
r
<message>Djssjs</message>
</time>
</person1>
<person2>
<time>
r
<message>1234fdg</message>
</time>
</person2>
<person1>
<time>
r
<message> talk 123</message>
</time>
</person1>
</messages>
我想在 html 文档中显示 talk 123 有点困惑该怎么做
//for form submit
$("#formpost").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: action.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
//for xml
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "name.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var msg = "";
//how to select the last person's of the <messages> child
msg = getElementsByTagName("messages").lastChild.childNodes[1].nodeValue ;
document.getElementById("demo").innerHTML = msg;
}
最佳答案
$("#formpost").on('submit', function(event){
event.preventDefault();
// rest of your ajax code here...
});
注意事项
1. 确保您在聊天页面的 head 标签上也添加了 JQuery 脚本源。
2. 确保在执行任何其他代码之前立即放置 preventDefault()。
关于javascript - 如何在不重新加载页面的情况下使用ajax聊天网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51608525/