从全局变量中的 AJAX 请求返回值
抱歉,如果这个问题重复,但我无法通过其他解决方案解决我的问题。
我在主索引中包含了一个单独的文件中包含此代码:
var getSuggestedData = {
serviceURL: $("input[name=suggestedServices]").val(),
dataR:"",
doRequest:function(){
//request data to controller
$.ajax({
url:this.serviceURL,
success:function(msg){
this.dataR = msg;
}
})
}
}
当我尝试以这种方式从索引中获取变量“dataR”时,它是未定义的!请问有人可以帮我吗?
$().ready(function() {
getSuggestedData.doRequest();
alert(getSuggestedData.dataR);
});
先感谢您!
Sorry if this question is duplicated but I couldn't solve my problem from other solutions.
I've got this code in a sepate file included in my main index:
var getSuggestedData = {
serviceURL: $("input[name=suggestedServices]").val(),
dataR:"",
doRequest:function(){
//request data to controller
$.ajax({
url:this.serviceURL,
success:function(msg){
this.dataR = msg;
}
})
}
}
When I'm trying to get the variable "dataR" from my index this way it's UNDEFINED! PLEASE, can someone help me out?
$().ready(function() {
getSuggestedData.doRequest();
alert(getSuggestedData.dataR);
});
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法访问 dataR 对象的原因是它与 success 方法返回的结果不在同一上下文中。
一种技术是在变量中保存对此的引用,如下所示:
您还可以查看下面的帖子,其中我详细解释了“this”关键字。
http://azamsharp.com/Posts/57_I_mean__this__not__this_.aspx
The reason you are not able to access the dataR object is because it is not in the same context as the result returned from the success method.
One technique is to hold a reference to this in a variable as shown below:
You can also check out the post below in which I explained in detailed about the "this" keyword.
http://azamsharp.com/Posts/57_I_mean__this__not__this_.aspx
如果我没记错的话...
可能需要是
对提供给 jQuery 的对象的“this”引用,您需要引用原始对象。我忘记您是否可以像这样直接通过名称访问它,或者如果您需要使用其他方法,请告诉我如果它不起作用。
If memory serves me right...
probably needs to be
the 'this' reference would be to the object fed to jQuery, you need to reference the original object. I forget if you could access it by its name directly such as this or if you need to use another method, let me know if it doesn't work out though.