无法从 JavaScript 函数返回对象的值
我有一个函数尝试通过以下方式从调用函数捕获返回值:
var select = xhrRetrieve(projID);
这是 xhrRetrieve 函数的示例:
function xhrRetrieve(projID) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var obj = $.parseJSON(xhr.responseText);
return obj.select.toString();
}
}
}
var url = "ajax.cgi";
var data = "action=retrieve-opp&proj-id=" + projID;
xhr.open("POST",url);
xhr.setRequestHeader("Content-Type","application/x-www-urlencoded");
xhr.send(data);
}
我将 jQuery 与直接 JavaScript 结合使用。每当我尝试使用以下方法获取 obj.select 的值时:
var select = xhrRetrieve(projID);
Select 总是返回 undefined
。
我做错了什么?
I have a function which attempts to capture a return value from a calling function in the following manner:
var select = xhrRetrieve(projID);
Here is an example of the xhrRetrieve function:
function xhrRetrieve(projID) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var obj = $.parseJSON(xhr.responseText);
return obj.select.toString();
}
}
}
var url = "ajax.cgi";
var data = "action=retrieve-opp&proj-id=" + projID;
xhr.open("POST",url);
xhr.setRequestHeader("Content-Type","application/x-www-urlencoded");
xhr.send(data);
}
I am using jQuery in conjunction with straight JavaScript. Whenever I attempt to get the value of obj.select using:
var select = xhrRetrieve(projID);
Select always comes back undefined
.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
select
。与此同时,您的 ajax 请求正在被触发,这需要时间才能完成;在 ajax 请求完成(并成功)之前,回调函数不会被调用。这应该有效:
select
. At the same moment, your ajax request is being fired, which takes time to complete; the callback function will not be called until the ajax request has completed (and succeeded).This should work:
由于请求是异步的,该函数将在 onreadestatechange 中的代码触发之前返回。您可以切换到同步并在函数返回之前获取值:
Since the request is asynchronous the function will return before your code in onreadestatechange fires. You can switch to synchronous and get the value before the function returns:
函数 xhrRetrieve 没有返回值。您预计会发生什么?
The function xhrRetrieve doesn't have a return value. What do you expect to happen?
你在那里有两个功能。内部函数返回一个值,但外部函数不返回值。内部函数是一个事件处理程序,因此返回值不会去任何地方。您的 XMLHttpRequest 是异步的,因此您不会立即获得返回值。有关更详细的说明,请参阅这篇文章: xmlHttpRequest 中的参数“true”。 open()方法
You have two functions there. The inner function returns a value, but not the outer one. The inner function is an event handler so the return value doesn't go anywhere. Your XMLHttpRequest is asynchronous, so you won't get a return value right away. See this post for a more detailed explanation: parameter "true" in xmlHttpRequest .open() method