我怎么能回返的一个变量美元的.getJSON功能
-
09-06-2019 - |
题
我想回到 StudentId
到其他地方使用外面的 范围 的 $.getJSON()
j.getJSON(url, data, function(result)
{
var studentId = result.Something;
});
//use studentId here
我会想象这与范围界定,但它似乎没有工作相同的方式 c# 做
解决方案
是啊,我以前的答案不起作用,因为我没注意到你的代码。:)
问题是,匿名的功能是一回拨功能--即getJSON是异步操作,这将返回在某一不确定的时间点,因此即使范围的变量之外的,匿名的功能(即一个封闭的),就不会有价值的你会认为它应该:
var studentId = null;
j.getJSON(url, data, function(result)
{
studentId = result.Something;
});
// studentId is still null right here, because this line
// executes before the line that sets its value to result.Something
任何你想要执行的价值studentId设getJSON呼吁需要发生 内 这回呼功能或 后 回调执行。
其他提示
它似乎并不以相同方式工作 c#不会
要完成划定范围的类似C#、禁用异步行动和设置数据类型叉:
var mydata = [];
$.ajax({
url: 'data.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json.whatever;
}
});
alert(mydata); // has value of json.whatever
甚至更简单于所有上述内容。如前面解释的 $.getJSON
执行异,其原因的问题。而不是重构所有你的代码 $.ajax
方法只是插入以下在你主。js文件禁用的异行为:
$.ajaxSetup({
async: false
});
祝你好运!
如果你希望委托给其他功能还可以延长jquery美元.fn。符号像这样:
var this.studentId = null;
$.getJSON(url, data,
function(result){
$.fn.delegateJSONResult(result.Something);
}
);
$.fn.delegateJSONResult = function(something){
this.studentId = something;
}
var context;
$.ajax({
url: 'file.json',
async: false,
dataType: 'json',
success: function (json) {
assignVariable(json);
}
});
function assignVariable(data) {
context = data;
}
alert(context);
嗯,如果你化的一个目的 StudentId
酒店那么我认为它将是:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0].StudentId;
}
但如果你刚刚回来的 StudentId
本身可能就是:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0];
}
编辑:或者也许 .length
甚至不是必需的(我只返回的一般收藏的关系图来描述软件所需的依赖).
编辑#2,这一工作,我刚测试:
var studentId;
jQuery.getJSON(url, data, function(json) {
if (json)
studentId = json;
});
编辑#3,这里的实际JS我的使用:
$.ajax({
type: "POST",
url: pageName + "/GetStudentTest",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
alert(json);
}
});
和在aspx。vb:
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function GetStudentTest(ByVal id As String) As Integer
Return 42
End Function
不隶属于 StackOverflow