我正在网上冲浪如何使用Stripes使用AJAX并找到this。但是,该文档解释了使用Prototype框架作为客户端脚本。不是Javascript。但我想用javascript代替。
我认为这个块使用Prototype库。
<script type="text/javascript"
src="${pageContext.request.contextPath}/ajax/prototype.js"></script>
<script type="text/javascript" xml:space="preserve">
/* ... */
function invoke(form, event, container) {
if (!form.onsubmit) { form.onsubmit = function() { return false } };
var params = Form.serialize(form, {submit:event});
new Ajax.Updater(container, form.action, {method:'post', parameters:params});
}
</script>
如何将其更改为javascript?或者我误解了什么。 我的主要目标是当用户单击我想将该数据发送到服务器并将其显示在表上而不刷新整个页面的按钮时。我有一个将保存数据的ActionBean。
谢谢。
答案 0 :(得分:1)
如果你不打算导入一个库(我建议使用它,因为这个代码对于非JS程序员来说可能有点重),那么你需要自己构建XMLHttpRequest对象。有一个good guide over at MDN涵盖了基础知识,但通常是这样做的:
// Build the object
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// Add the function for handling changes to state
httpRequest.onreadystatechange = function () {
// Check the state of the request
if (httpRequest.readyState === 4) {
// The server has finished sending data and we are ready to handle it
if(httpRequest.status < 400) {
// Request was successful, Put your code for handling the response here
// String of what the response was will be in httpRequest.responseText
} else {
// Request was not successful, probably want to display an error
}
} else {
// Response is still being received and is not quite ready yet.
}
}
// Now that we can handle it, we want to send the request
httpRequest.open("GET", "http://example.com");
// Don't forget to send it :)
httpRequest.send();
如您所见,它不是最简单的代码。我强烈建议您阅读MDN page on the subject,因为它可以帮助您理解上面的代码。它可以帮助您做更多的事情,比如发送数据和您的请求。这里不是序列化和提交表单不仅仅是我上面的例子。如果您想提交表格,您需要确保仔细阅读该文章。
为什么我推荐像Prototype或jQuery这样的JS库是因为它们使所有这些(以及更多)变得更加简单。