
[英]How to read a return value from another function in another javascript file
[英]access return value of function from another file
我有一个js文件,其代码为:
function postResponse(url1,param1)
{
var url = intranetUrl + encodeURI(url1);
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function(e)
{
if (this.status == 200)
{
genericRes = this.responseText;
console.log("inside fun:"+genericRes);
return genericRes;
}
alert("!!!"+this.status);
};
xhr.send(param1);
}
现在我要从另一个文件访问此函数,我已经在该文件中的文件上方导入了该文件,并调用函数为:
<script type="text/javascript">
var resss = postResponse("myURL","ACC|^ALL|^M|^|$");
alert("genericRes"+genericRes);
console.log("genericRes>>>"+genericRes);
console.log("resss>>>"+resss);
</script>
但是在这里,我得到了genericRes和resss值未定义的信息,上面console.log先打印,然后再打印console.log("inside fun:"+genericRes);
在这里,我得到了正确的输出,但是通过调用代码,它给了我未定义的信息。
在Java中,我们编写了suppose方法,该方法可以将String返回为:
public String myMethod()
{
str = "MyString";
return str;
}
并按以下方式调用该方法:
String str1 = myMethod();
但是如何在jquery中做到这一点?
任何建议将不胜感激。 提前致谢
如果仔细看,您正在定义另一个函数,如:
function(e) //<-- this is the another function
{
if (this.status == 200)
{
var genericRes = this.responseText;
console.log("inside fun:"+genericRes);
return genericRes; //<-- this only applies to this function
}
alert("!!!"+this.status);
};
因此它将把该值返回给xhr.onload
的调用者,该调用者是浏览器,浏览器对返回值不做任何事情。
此外,您不能真正从异步操作中返回,而必须使用回调。
所以:
function postResponse(url1, param1, callback) { // <-- take a callback parameter
var url = intranetUrl + encodeURI(url1);
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function(e) {
if (this.status == 200) {
var genericRes = this.responseText;
callback( genericRes ); // <-- call the callback
}
};
xhr.send(param1);
}
然后在您的代码中:
postResponse("myURL", "ACC|^ALL|^M|^|$", function(result) {
alert(result); //Result is only available here. In this anonymous function defined inline. Yes.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.