通过 AJAX 发送的字符串中的 JS 运算符导致请求失败

JS operators in string sent through AJAX causing request to fail

我制作了一个密码管理器,但如果它包含任何类型的 javascript 运算符,则无法完全提取密码。我想进行 AJAX 调用,但如果我输入字段中的字符串包含 + 或任何其他运算符,该字符串就会停止。如何忽略运算符是字符串?

if ($("#editpswform").data("changed")) {
  id = $('#passid').text();
  name = $('#pswname').val();
  url = $('#pswurla').text();
  username = $('#pswusr').val();
  password = $('#pswi').val();
  notes = $('#pswnotes').val();
  var dataString = 'EditPSW=true' + '&id=' + id + '&name=' + name + '&url=' + url + '&username=' + username + '&password=' + password + '&notes=' + notes;

  $.ajax({
    type: "POST",
    url: "utils.php",
    data: dataString,
    success: function(msg) {
      console.log(msg);
      $.ajax({
        url: "utils.php?setsession=Password saved!"
      }).done(function() {
        load_data();

        function load_data(query) {
          $.ajax({
            url: "search.php",
            method: "POST",
            data: {
              query: query
            },
            success: function(data) {
              $('#contentmain').html(data);
            }
          });
        }

        OpenNotification();
      });
    },
    error: function() {
      $.ajax({
        url: "utils.php?setsession=Error saving password!",
      }).done(function() {
        OpenNotification();
      });
    }
  });
} else {
  $.ajax({
    url: "utils.php?setsession=No changes made!",
  }).done(function() {
    OpenNotification();
  });
}

您可能需要对 URL 中的每个值进行编码。像这样:

var dataString = 'EditPSW=true' + '&id=' + encodeURIComponent(id) + '&name=' + encodeURIComponent(name) + '&url=' + encodeURIComponent(url) + '&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password) + '&notes=' + encodeURIComponent(notes);

这个问题听起来像是查询字符串中值的编码问题。改为发送对象中的值。这样您就可以避免丑陋的连接逻辑,并且 jQuery 将为您正确编码值。

var dataString = {
  EditPSW: true,
  id: id,
  name: name,
  url: url,
  username: username,
  password: password,
  notes: notes
}