【问题标题】:Stripes and Ajax- How do i send data to a server and refresh a table with data using AJAXStripes 和 Ajax - 如何将数据发送到服务器并使用 AJAX 刷新数据表
【发布时间】:2012-02-16 18:06:29
【问题描述】:

我在网上浏览如何使用带有条纹的 AJAX 并找到this。然而,文档解释了使用 Prototype 框架作为客户端脚本。不是Javascript。但我想改用javascript。

我认为这个块使用原型库。

<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。

谢谢。

【问题讨论】:

  • Prototype.js 是一个 JavaScript 库(正如扩展程序可能暗示的那样)
  • 是的。这是正确的。由于我不能使用其他框架,我可能不得不在不使用外部库的情况下这样做。
  • 所以你想改变它 JavaScript,没有任何库?
  • 我所知道的是,我无法将新库导入我们的应用程序。这意味着如果我想使用上面的代码,我必须导入 Prototype 框架。如果可能,我必须编写纯 JavaScript 而不是导入新库或调用 java-script 函数(如果存在)。我不确定我是否回答了你的问题。

标签: javascript ajax client-side stripes


【解决方案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 库是因为它们使所有这些(以及更多)变得更简单。

【讨论】:

    猜你喜欢
    • 2021-03-22
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2023-04-02
    • 1970-01-01
    • 2011-09-17
    相关资源
    最近更新 更多