javascript - 为什么我的 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);
}
请帮忙
解决方案
我希望这对你来说清楚:)
在 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(); }; };
推荐阅读
- r - 使用textmineR的LDA模型中每个文档的主题标签
- php - 如何让当前用户全名显示在表单验证消息中
- list - 从 Prolog DCG 创建列表
- c - 程序从文件读取时显示随机列表数据
- c# - FTP、GetRequestStream()、非英文字符时报错550
- arrays - 从 ArrayList 中查找最大值
- python - 如何在 ebaysdk 上导入产品 API?
- c# - Unity IAP:如何编写脚本来为当前版本的 Unity 提供无代码 IAP 功能?
- python - 将其他数据嵌入到 UDP 视频流 Python OPENCV
- laravel - 为什么 Eloquent HasMany 返回一个空集合?