前端设计:动态添加项目到列表

Front-end design: Dynamically add items to list

因此,我曾多次尝试将自己投入网站开发的世界。每次,我都出于一个简单的原因放弃了一个项目:列表。

我想知道,从前到后,遵循以下事件顺序的系统的数据流:

  1. 用户在网站中显示列表
  2. 用户在某种模式对话框中填写新的列表项
  3. 用户点击 "Submit",该项目现已添加到列表中。
    • 新的列表项被发送到服务器进行存储

是否会加载全新的页面?什么时候将数据发布到服务器?这个(看似简单的)应用程序有哪些不同的选项?我的目标是相对较小的网络工具。不一定是单页,但我不反对。

我知道如何使用 JQuery 将新的 <li> 添加到列表中,并且我知道如何使用 HTML 构建模式。我可以从模式中提取数据,但我不确定如何从 JQuery 中获取数据,将其转换为 HTML 的适当块(这可能相当复杂),并存储数据库中的新记录。 我似乎找不到关于这种数据处理的教程。

谢谢!

简单。既然你提到了jQuery,那我们就用jQuery吧。准备好?我们开始了!

我假设您的模式中有一个 textareainput,用户可以在其中输入文本。如果是这样,给它一个 id 属性以便它可以被引用,比如 id="myText"

然后,要获取 textareainput 的内容并将其变成列表中的列表项,您需要在文本区域的其父 <ul> 标签的内容。同样,你需要一些方法来引用 <ul> 标签,所以给 <ul> 标签一个 id 属性,比如 myList,所以它变成 <ul id="myList">.

现在,只需从输入字段中取出 val()ue,并将其附加到列表中即可。这就是你的做法。

var textareaStuff = $('#myText').val();
$('#myList').append('<li>'+textareaStuff+'</li>');

这并不难,不是吗?这个其实挺好玩的。

我承认,将内容发布到服务器可能需要一些时间来适应,但这并不难。

我已经为您准备了一个 HTML 文件来执行所有这些操作,并提供了非常详细的文档。它应该能够帮助你学习你想学的东西。在下面。

<!DOCTYPE html>
<html>

<head>
  <title>My jQuery Experiments</title>
</head>

<body>

  <!-- Here's your list with its ID so we can reference it in JS. -->
  <ul id="myList">
    <li>Sample Item 1</li>
  </ul>
  <input id="myText"> <!-- Here's your input field. This can be in a modal. -->
  <button id="addItemButton">Add Item</button> <!-- We need a save button. -->

  <!-- Include jQuery -->
  <script type="text/javascript"
          src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

  <!-- This is the javascript you'll need to write and understand -->
  <script type="text/javascript" >

    // When the element with id="addItemButton" is clicked,
    $('#addItemButton').click(function() {

      // Append the stuff in brackets to the element with id="myList"
      $('#myList').append('<li>' + $('#myText').val() + '</li>');

      // ^ The stuff in brackets is an li code with the value of the HTML
      // element with id="myText", your input field above.

      // Now to post it to a server, we'll need to use AJAX.
      // Luckily, jQuery has an AJAX function. It looks like this:

      $.ajax('http://example.com/mysaver.php', {

        // We're POSTing stuff to the server.
        method: 'post',

        // This is the data to send to the server.
        // It is a JSON object. 
        // If using PHP, you'll get $_POST['item'] = whatever is in id="myText"
        data: { item: $('#myText').val() },

        // If the AJAX request was successful,
        success: function(data) {
          // The argument 'data' contains whatever the server returned. 
        },

        // If not,
        error: function(jqXHR) {
          // Handle your error here.
        }
      });

    });

  </script>
</body>

</html>

希望对您有所帮助!继续并批准这个答案,如果有的话,请随时在评论中提出更多问题,我会尽我所能提供帮助。