我一直在尝试学习 ajax,从我可以看到我的代码是正确的,但是当它回显返回的 json 字符串时,它总是刷新页面。任何帮助将不胜感激!
<script>
// Get XML HTTP Type
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxSuccess () {
alert(this.responseText);
}
function ajaxrequest(oFormElement) {
//Get The Correct XMLHTTP Object
var request = new XMLHttpRequest();
request.open(oFormElement.method, oFormElement.action, true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(new FormData(oFormElement));
return false;
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
alert("done");
document.getElementById('comment_form').innerHTML = request.responseText;
}
}
}
</script>
<form action="<?php echo $add_comment; ?>" method="post" enctype="multipart/form-data" id="comment_form" onsubmit="ajaxrequest(this);">
<input name="user_id" type="hidden" value="<?php echo $user_id; ?>">
<input name="user_message_id" type="hidden" value="<?php echo $user_message_id; ?>">
<textarea id="new_comment" name="new_comment" cols="100" rows="5"></textarea>
<input type="submit" value="post request"/>
</form>
您必须阻止事件发生。 在 JavaScript 中有一个常用的函数:
e.preventDefault; // e is the event that you need to pass to your function.
或更改
<input type="submit" value="post request"/>
自
<input type="button" onclick="ajaxrequest(this);" value="post request"/>
将要发生的事情是,您的表单只会由JavaScript处理,并且由于表单提交,页面将重新加载。
只需为自己修改此方法,它应该可以解决您的问题。
使用 Jquery 库 http://api.jquery.com/jQuery.ajax/,但如果你想构建自己的脚本。 请参阅 W3C 文档 http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
正如 Pointy 指出的那样,您可能希望阻止提交按钮的默认单击事件触发
submitForm( event ) {
event.preventDefault();
}
http://api.jquery.com/event.preventDefault/ <- 我的坏...
只是为了澄清,这是您的完整代码吗?