Javascript 将数据集从函数返回到 xmlhttprequest 获取参数
我有一个用 php 变量填充的数据属性。 php 变量是一个数值。
<?php $userId = 123; ?>
<div class="agent-detail-info" data-id="<?= $userId ?>"></div>
我试图从数据集中获取值并将其传递给 get url 参数。我已将其放入 window.onload 自己的函数中,因为 php 会动态打印 html。
function userData() {
let infoWrap = document.querySelector(".agent-detail-info").dataset.id;
console.log(infoWrap);
return infoWrap;
}
window.onload = userData;
const request = new XMLHttpRequest();
request.open(
"GET",
`url&usertolookup=${userData()}`
);
Console.log(infoWrap) 在控制台中返回正确的值,但控制台显示错误并且不填充获取参数
Uncaught TypeError: Cannot readproperties of null (reading 'dataset') at userData
I'我认为发生这种情况是因为请求在调用 userData 函数之前运行并且 DOM 尚未填充?
这是有效的:
function userData() {
let infoWrap = 123;
return infoWrap;
}
我尝试将请求包装到加载 DOM 后运行的函数中,但这也不起作用。
I have a data attribute that is populated with a php variable. The php variable is a numeric value.
<?php $userId = 123; ?>
<div class="agent-detail-info" data-id="<?= $userId ?>"></div>
I am trying to grab the value from the dataset and pass it to a get url parameter. I've put this into its own function for window.onload as the php prints the html dynamically.
function userData() {
let infoWrap = document.querySelector(".agent-detail-info").dataset.id;
console.log(infoWrap);
return infoWrap;
}
window.onload = userData;
const request = new XMLHttpRequest();
request.open(
"GET",
`url&usertolookup=${userData()}`
);
Console.log(infoWrap) returns the correct value in console, but console shows an error and does not populate the get parameters
Uncaught TypeError: Cannot read properties of null (reading 'dataset') at userData
I'm thinking this is happening because the request is running before the userData function is called and the DOM is not yet populated?
This works:
function userData() {
let infoWrap = 123;
return infoWrap;
}
I tried wrapping the request into a function that runs after the DOM is loaded but this also did not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在
window.onload
末尾运行代码,以便它在.agent-detail-info
元素添加到 DOM 后运行。运行userData()
本身不会执行任何操作。You should run the code at the end from
window.onload
, so it runs after the.agent-detail-info
element is added to the DOM. RunninguserData()
itself doesn't do anything.