开发者问题收集

使用动态生成的JSON的AJAX帖子未向后端发射

2020-07-27
206

总体而言,对 Bootstrap 和 FE 开发还是比较陌生的。我有以下页面向用户显示一个表格,表格中的每一行都有一个“ 更改 ”按钮,如下所示:

在此处输入图像描述

当用户点击更改按钮时,他们会看到一个模式,如下所示:

在此处输入图像描述

然后,他们可以更改配置的值并点击 更新 按钮,我希望 AJAX 帖子将一些 JSON 提交给某个url。

这是我最好的尝试:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

    <meta name="description" content="">
    <meta name="author" content="">

    <title>My App</title>

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">


</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top">
    <div class="container">
        <a class="navbar-brand" href="/">My App</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive"
                aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/fizzes">Fizzes</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/buzzes">Buzzes</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div class="container">

    <div class="row">
        <div class="col-md-4 mt-5">
            <h3><span>Configurations</span></h3>
            <table class="table">
                <thead>
                <tr>
                    <th scope="col">Config</th>
                    <th scope="col">Value</th>
                    <th scope="col">Actions</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td >type</td>
                    <td >EXCEL</td>
                    <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#changeModal" data-currval="EXCEL" data-config="type">Change</button></td>
                </tr>
                <tr>
                    <td >fizz</td>
                    <td >1</td>
                    <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#changeModal" data-currval="1" data-config="fizz">Change</button></td>
                </tr>
                </tbody>
            </table>
            <button>Config History</button>
        </div>
    </div>

</div>

<div class="modal fade" id="changeModal" tabindex="-1" role="dialog" aria-labelledby="changeModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changeModalLabel">Change config value</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="current-value" class="col-form-label">Current value:</label>
                        <input type="text" class="form-control" id="current-value"/>
                    </div>
                    <div class="form-group">
                        <label for="new-value" class="col-form-label">New value:</label>
                        <textarea class="form-control" id="new-value"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" id="btnUpdate" class="btn btn-primary">Update</button>
            </div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
    $('#changeModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var configName = button.data('config');
        var currVal = button.data('currval');
        var modal = $(this);
        modal.find('.modal-title').text('Change value for ' + configName);
        modal.find('.modal-body input').val(currVal);
    });

    $('#btnUpdate').click(function (event) {
        var button = $(event.relatedTarget);
        var modal = $(this);
        var url = '/fizzes/abc123/buzzes/abc235';
        var configName = button.data('config');
        var newVal = modal.find('#new-value').text;

        $.post(
            url,
            { [configName]: newVal },
            alert("update made")
        )
    });
</script>

</body>
</html>

当我在浏览器中运行此命令时,单击“更改”,更新值并单击“更新”,我得到了 alert("update made") 弹出窗口,但在我的开发人员工具网络选项卡中我实际上并没有看到 AJAX POST 触发,而是看到以下错误:

Uncaught TypeError: Cannot read property 'length' of undefined
    at $ (jquery.min.js:2)
    at text (jquery.min.js:2)
    at i (jquery.min.js:2)
    at Dt (jquery.min.js:2)
    at Function.S.param (jquery.min.js:2)
    at Function.ajax (jquery.min.js:2)
    at Function.S.<computed> [as post] (jquery.min.js:2)
    at HTMLButtonElement.<anonymous> (abc235:121)
    at HTMLButtonElement.dispatch (jquery.min.js:2)
    at HTMLButtonElement.v.handle (jquery.min.js:2)

在服务器端我也没有看到收到任何请求。我注意到,在我的 IDE 中,当我将鼠标悬停在 AJAX 帖子的 [configName] JSON 部分上时,我看到以下错误:

" Computed property names are not supported by current JavaScript version "

所以我尝试将其更改为:

$.post(
    url,
    { configName: newVal },
    alert("update made")
)

但问题仍然存在。有人能发现我哪里做错了吗?

3个回答

抱歉,我无法在 jQuery 中执行此操作,但这里有一个 AJAX 请求,它可以替换底部的整个 POST 请求:

function sendData(url, object) {
  const formdata = new FormData();
  for ( let key in object ) {
    formdata.append(key, object[key]);
  }
  
  const http = new XMLHttpRequest();
  return new Promise(resolve => {
    http.onreadystatechange = function () {
      if (this.readyState === 4 && this.status === 200) {
        resolve(this.responseText);
      }
    };
    http.open("POST", url, true);
    http.send(formdata);
  });
}

//object is post information

sendData(url, {
  [configName]: newVal
}).then(response => alert("Update made"));

//configName should be a string
luek baja
2020-07-27

我猜想 modal.find 在这里没有发挥作用。我找不到 modal 的函数来读取值,所以我使用了 jquery .val() 函数。

var newVal = $('#new-value').val();

希望这对你有用

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

    <meta name="description" content="">
    <meta name="author" content="">

    <title>My App</title>

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">


</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top">
    <div class="container">
        <a class="navbar-brand" href="/">My App</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive"
                aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/fizzes">Fizzes</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/buzzes">Buzzes</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div class="container">

    <div class="row">
        <div class="col-md-4 mt-5">
            <h3><span>Configurations</span></h3>
            <table class="table">
                <thead>
                <tr>
                    <th scope="col">Config</th>
                    <th scope="col">Value</th>
                    <th scope="col">Actions</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td >type</td>
                    <td >EXCEL</td>
                    <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#changeModal" data-currval="EXCEL" data-config="type">Change</button></td>
                </tr>
                <tr>
                    <td >fizz</td>
                    <td >1</td>
                    <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#changeModal" data-currval="1" data-config="fizz">Change</button></td>
                </tr>
                </tbody>
            </table>
            <button>Config History</button>
        </div>
    </div>

</div>

<div class="modal fade" id="changeModal" tabindex="-1" role="dialog" aria-labelledby="changeModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changeModalLabel">Change config value</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="current-value" class="col-form-label">Current value:</label>
                        <input type="text" class="form-control" id="current-value"/>
                    </div>
                    <div class="form-group">
                        <label for="new-value" class="col-form-label">New value:</label>
                        <textarea class="form-control" id="new-value"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" id="btnUpdate" class="btn btn-primary">Update</button>
            </div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
    $('#changeModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var configName = button.data('config');
        var currVal = button.data('currval');
        var modal = $(this);
        modal.find('.modal-title').text('Change value for ' + configName);
        modal.find('.modal-body input').val(currVal);
    });

    $('#btnUpdate').click(function (event) {
        var button = $(event.relatedTarget);
        var modal = $(this);
        var url = '/fizzes/abc123/buzzes/abc235';
        var configName = button.data('config');
        var newVal = $('#new-value').val();
        console.log(newVal)

        $.post(
            url,
            { [configName]: newVal },
            alert("update made")
        )
    });
</script>

</body>
</html>
Riddhijain
2020-07-29

真正需要修复的是提交时选择器的变化

var button = $(event.relatedTarget);

var element = $('input#current-value');

和变化

var configName = button.data('config');
var newVal = modal.find('#new-value').text;


var configName = element.val();
var newVal = $('textarea#new-value').val();

所以最后你的代码应该是这样的,它应该被修复

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <meta name="description" content="" />
    <meta name="author" content="" />

    <title>My App</title>

    <!-- Bootstrap core CSS -->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
  </head>
  <body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top">
      <div class="container">
        <a class="navbar-brand" href="/">My App</a>
        <button
          class="navbar-toggler"
          type="button"
          data-toggle="collapse"
          data-target="#navbarResponsive"
          aria-controls="navbarResponsive"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              <a class="nav-link" href="/fizzes">Fizzes</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="/buzzes">Buzzes</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>

    <div class="container">
      <div class="row">
        <div class="col-md-4 mt-5">
          <h3><span>Configurations</span></h3>
          <table class="table">
            <thead>
              <tr>
                <th scope="col">Config</th>
                <th scope="col">Value</th>
                <th scope="col">Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>type</td>
                <td>EXCEL</td>
                <td>
                  <button
                    type="button"
                    class="btn btn-primary"
                    data-toggle="modal"
                    data-target="#changeModal"
                    data-currval="EXCEL"
                    data-config="type"
                  >
                    Change
                  </button>
                </td>
              </tr>
              <tr>
                <td>fizz</td>
                <td>1</td>
                <td>
                  <button
                    type="button"
                    class="btn btn-primary"
                    data-toggle="modal"
                    data-target="#changeModal"
                    data-currval="1"
                    data-config="fizz"
                  >
                    Change
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
          <button>Config History</button>
        </div>
      </div>
    </div>

    <div
      class="modal fade"
      id="changeModal"
      tabindex="-1"
      role="dialog"
      aria-labelledby="changeModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="changeModalLabel">
              Change config value
            </h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form>
              <div class="form-group">
                <label for="current-value" class="col-form-label"
                  >Current value:</label
                >
                <input type="text" class="form-control" id="current-value" />
              </div>
              <div class="form-group">
                <label for="new-value" class="col-form-label">New value:</label>
                <textarea class="form-control" id="new-value"></textarea>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              Close
            </button>
            <button type="button" id="btnUpdate" class="btn btn-primary">
              Update
            </button>
          </div>
        </div>
      </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
      crossorigin="anonymous"
    ></script>
    <script type="text/javascript">
      $('#changeModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var configName = button.data('config');
        var currVal = button.data('currval');
        var modal = $(this);
        modal.find('.modal-title').text('Change value for ' + configName);
        modal.find('.modal-body input').val(currVal);
      });

      $('#btnUpdate').click(function (event) {
        var element = $('input#current-value');
        var modal = $(this);
        var url = '/fizzes/abc123/buzzes/abc235';
        var configName = element.val();
        var newVal = $('textarea#new-value').val();
        console.log(newVal);

        $.ajax({
          url: url,
          method: 'POST',
          data: { [configName]: newVal },
          success: (data) => {
            console.info(data);
          },
          error: (err) => {
            console.error(err);
          },
        });
      });
    </script>
  </body>
</html>

顺便说一句,你绝对可以忽略我使用的是 $.ajax 而不是你使用的帖子这一事实,这只是对我的一次健全性检查。

Toni
2020-08-05