首页 > 解决方案 > 为什么我的 JS 函数参数未定义?

问题描述

我有一个脚本加载接受好友请求,我的 onclick 功能是:

onclick="acceptfriendrequest('John');"

更多细节 :

echo  "<br><div style='width:100%; height: 30px;'><div class='userpic' style='background-image: url($avatar); margin-left: 10px; float: left;'></div><p class='incomingfriendrequests' style='float: left; margin-top: 7px; margin-left: 8px;'>$usernames</p><input type='submit' onclick='acceptfriendrequest($usernames)' style= 'margin-left: 10px; margin-top: 6.5px; float: left;' name='accept' value='Accept'><input type='submit' style= 'margin-left: 10px; margin-top: 6.5px; float: left;' name='deny'onclick='declinefriendrequest($usernames)'  value='Deny'></div>";

但由于某种原因,我的控制台显示:未捕获的 ReferenceError:John 未在 HTMLInputElement.onclick 中定义。

这是它链接到的功能:

function acceptfriendrequest(username) {
  var fd = new FormData();
  fd.append("username", username);
  fd.append("accept", true);
  var xhr = new XMLHttpRequest();
  var fullurl = '../backend/friends.php';
    xhr.open('POST', fullurl, true);
    xhr.onload = function() {
      if (this.status == 200) {
        loadfriends();
      };
  };
  xhr.send(fd);


}

请帮忙

标签: javascript

解决方案


我希望这对你来说清楚:)

  • 在 HTML onclick 中,您需要放置不带任何参数或 () 的函数:

     // function without () or arguments
     onclick=acceptfriendrequest
    
  • 在 JavaScript 中,在函数中使用变量中的参数,然后在函数中使用此变量作为参数:

    // variables as argument     
    let username = "Name";
    
    // function without arguments
    function acceptfriendrequest() {
    
      // use variables in function :)
      var fd = new FormData();
      fd.append("username", username);
      fd.append("accept", true);
      var xhr = new XMLHttpRequest();
      var fullurl = '../backend/friends.php';
      xhr.open('POST', fullurl, true);
      xhr.onload = function() {
        if (this.status == 200) {
          loadfriends();
        };
    };
    

推荐阅读