gpt4 book ai didi

javascript - 如何将参数从一个函数发送到另一个函数

转载 作者:行者123 更新时间:2023-11-28 13:36:46 25 4
gpt4 key购买 nike

如何从函数 func() 获取 par 值并使用它附加到另一个函数 handlerFunction() 中的 a_span 元素。par 是一个 ID。在 handlerFunction() 中,我需要获取 a_spanID

例如:

document.getElementById('a_span35')

function func(par) {
XMLHttp.open("POST", "some.php");
XMLHttp.onreadystatechange = handlerFunction();
XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XMLHttp.send("post_name="+par);
}

function handlerFunction() {
if (XMLHttp.readyState == 4) {
document.getElementById('a_span').innerHTML=XMLHttp.responseText;
}
}

最佳答案

最简单的方法是将 handlerFunction 放在 func 内部,这样它就会在 par 上关闭(但我'下面将给您一个替代方案):

function func(par) {
XMLHttp.open("POST", "some.php");
XMLHttp.onreadystatechange = handlerFunction;
XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XMLHttp.send("post_name=" + par);

function handlerFunction() {
// You can use `par` here, even though `func` has already returned
if (XMLHttp.readyState == 4) {
document.getElementById('a_span').innerHTML = XMLHttp.responseText;
}
}

}

handlerFunction 是对 func 调用上下文的闭包。不用担心这个词,closures are not complicated .

<小时/>

另请注意,您的代码中有一个错误,我已在上面更正了该错误:您有

XMLHttp.onreadystatechange = handlerFunction();

...立即调用 handlerFunction 并将其返回值分配给onreadystatechange(与x = foo() 完全相同) ; 调用 foo 并将返回值分配给x)。应该是:

XMLHttp.onreadystatechange = handlerFunction;
<小时/>

我假设您正在某处创建 XMLHttp (我建议为每次调用 func 创建一个新的,而不是重复使用一个)。

<小时/>

替代方案:

您可以通过将 handlerFunction 的调用包装在另一个函数中(手动)来保持其独立:

function func(par) {
  XMLHttp.open("POST", "some.php");
  XMLHttp.onreadystatechange = function() {
handlerFunction(XMLHttp, par);
};
  XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  XMLHttp.send("post_name=" + par);
}

function handlerFunction(xhr, par) {
  if (xhr.readyState == 4) {
// use par
    document.getElementById('a_span').innerHTML = xhr.responseText;
  }
}

...或使用 ES5 的 Function#bind:

function func(par) {
  XMLHttp.open("POST", "some.php");
  XMLHttp.onreadystatechange = handlerFunction.bind(undefined, XMLHttp, par);
  XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  XMLHttp.send("post_name=" + par);
}

function handlerFunction(xhr, par) {
  if (xhr.readyState == 4) {
// use par
    document.getElementById('a_span').innerHTML = xhr.responseText;
  }
}

您需要在 native 没有的浏览器上使用 Function#bind 填充程序。 bind 的作用是返回一个函数,该函数在调用时会使用给定的 this 值(第一个参数)以及为其提供的参数来调用原始函数。

关于javascript - 如何将参数从一个函数发送到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20860739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com