javascript - 处理 ajax PUT 请求

标签 javascript jquery ajax express

编辑:将 $(this).attr('red') 传递给变量后,不再获得未定义的 URI。但仍然收到 500 服务器错误。

编辑:Here is all the code on github (以防万一我错过了什么!)

编辑:这是在 global.js 中调用该函数的方式

$('#userList table tbody').on('click', 'td a.linkedituser', editUser);

这是 html。

<div id="wrapper">
    <div id="userInfo">
      <h2>User Info</h2>

      <p><strong>Name:</strong> <span id='userInfoName'></span><br />
      <strong>Age:</strong> <span id='userInfoAge'></span><br />
      <strong>Gender:</strong> <span id='userInfoGender'></span><br />
      <strong>Location:</strong> <span id='userInfoLocation'></span></p>
    </div>

    <h2>User List</h2>

    <div id="userList">
      <table>
        <thead>
          <tr>
            <th>UserName</th>

            <th>Email</th>

            <th>Delete</th>

            <th>Edit</th>
          </tr>
        </thead>
      </table>
    </div>

    <h2>Edit User</h2>

    <div id="editUser">
      <fieldset>
        <input id="editUserName" type="text" placeholder="Username" /><input id=
        "editUserEmail" type="text" placeholder="Email" /><br />
        <input id="editUserFullname" type="text" placeholder="Full Name" /><input id=
        "editUserAge" type="text" placeholder="Age" /><br />
        <input id="editUserLocation" type="text" placeholder="Location" /><input id=
        "editUserGender" type="text" placeholder="Gender" /><br />
        <button id="btnEditUser">Edit User</button>
      </fieldset>
    </div>
</div>

我正在尝试提交表单作为 PUT 请求来编辑用户信息。

提交表单时,我在 Chrome 控制台中收到以下错误。

[Error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (undefined, line 0)

错误的右侧显示了 ID,所以我想这与路由器端有关?

http://localhost:3000/users/edituser/53fa0acbc069f52257312d2c

这是我的客户端函数。

function editUser(event) {

event.preventDefault();

var thisUserID = $(this).attr('rel');
var arrayPosition = userListData.map(function(arrayItem) { return arrayItem._id;    }).indexOf(thisUserID);

var thisUserObject = userListData[arrayPosition];

$('#editUserName').val(thisUserObject.email);
$('#editUserEmail').val(thisUserObject.email);
$('#editUserFullname').val(thisUserObject.fullname);
$('#editUserAge').val(thisUserObject.age);
$('#editUserLocation').val(thisUserObject.location);
$('#editUserGender').val(thisUserObject.gender);

var editUser = {
  'username' : $('#editUserName').val(),
  'email' : $('#editUserEmail').val(),
  'fullname' : $('#editUserFullname').val(),
  'age' : $('#editUserAge').val(),
  'location' : $('#editUserLocation').val(),
  'gender' : $('#editUserGender').val(),
}

//just a test to prove that I can read the id from the db
$('body > h1').text($(this).attr('rel'));

$('#btnEditUser').on('click', function() {
  $.ajax({
    type: 'PUT',
    url: '/users/edituser/' + thisUserID,
    data: JSON.stringify(editUser),
    dataType: 'json',
    success: function(msg) { alert('Success'); },
    error: function(err) {alert('Error'); }
  }).done(function(response) {
    if (response.msg === '') {
    }
    else {
      alert('Error: ' + response.msg);
    } 
    populateTable();
  });
});
};

这是我的路由器位于/routes/users.js 内的服务器端。

router.put('/edituser/:id', function(req, res) {
    var db = req.db;
    var userToEdit = req.params('id');

    db.collection('userlist').findById(userToEdit, function(err, result) {
        res.send((result === 1) ? { msg: '' } : { msg: 'error: ' + err });
    });
});

有人可以帮忙吗?谢谢!

最佳答案

id 位于 url 中时,您将从正文中提取该 id

因此将 var userToEdit = req.body.id; 替换为:

var userToEdit = req.params.id;

或者您可以使用 req.param('id') ,它会经过 all the methods找到值。

还可以使用 res.json(..) 而不是 res.send(..)

关于javascript - 处理 ajax PUT 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25486686/

相关文章:

javascript - 如何使用 jquery 将标题大小写文本输出到 html 字段中

javascript - 数据列表字序

jquery - 在 jQuery 中切换 2 个类的最简单方法

javascript - 当我通过 ajax 使用跨域调用通用处理程序时,在 ajax 成功时数据未定义

javascript - 是否有可能知道函数是否是从引用中调用的?

javascript - 取消选中复选框时从广播中删除 "checked"

javascript - knockout 'textInput' 和 'Value' 绑定(bind)未捕捉到 JS 所做的更改

javascript - 等待 jquery .html 方法完成渲染

php检测/获取发布请求的发件人url(或服务器)

javascript - 有没有办法使用 XMLHttpRequest() 将 json 发送到远程 cfc?