Jquery 使用不同变量的多个ajax调用成功
更新:问题在其他地方。我打了3个相同属性的电话。因此,如果您有相同的问题,请检查$.ajax之前的属性值 我有一个jQuery ajax调用:Jquery 使用不同变量的多个ajax调用成功,jquery,ajax,variables,Jquery,Ajax,Variables,更新:问题在其他地方。我打了3个相同属性的电话。因此,如果您有相同的问题,请检查$.ajax之前的属性值 我有一个jQuery ajax调用: function foo(someVar){ $.ajax({ dataType: "json", url: 'http://some.json?callback=?', success: function(data){ alert(someVar); }
function foo(someVar){
$.ajax({
dataType: "json",
url: 'http://some.json?callback=?',
success: function(data){
alert(someVar);
}
});
}
getPriceByRoute('a');
getPriceByRoute('b');
getPriceByRoute('c');
如果进行多次呼叫:
function foo(someVar){
$.ajax({
dataType: "json",
url: 'http://some.json?callback=?',
success: function(data){
alert(someVar);
}
});
}
getPriceByRoute('a');
getPriceByRoute('b');
getPriceByRoute('c');
将通过c
获得3个警报
如何将我的someVar
发送到成功功能?
尝试做:
function foo(someVar){
$.ajax({
dataType: "json",
//
myVars:{someVar:someVar},
//
url: 'http://some.json?callback=?',
success: function(data){
alert(this.myVars.someVar);
}
});
}
但同样的结果
在最后一种情况下,我可以在上一次加载后发送下一个请求,但希望还有其他好的解决方案。使用
$中的上下文选项。ajax
$.ajax({
...
context: {someVar:someVar}, // sets the value of "this" inside the success function
...
success: function(data){
// "this" is {someVar:someVar}, as set via the context option
alert(this.someVar);
}
});
诺雷波:@Juhana,很抱歉,服务器上有病毒,有些网站不工作。jsfiddle就是其中之一:)关键是,如果我调用foo('a');foo('b');foo('c')代码>我得到了a、b和c的警报(以不同的顺序),因为它们应该得到警报。您确定这就是您的代码吗?是的,它可能直接返回响应,请尝试添加其他json服务器,例如https://api.twitter.com/1/statuses/user_timeline.json?screen_name=narekmarkosyan&count=4&calback=?
这没什么区别。该变量是本地变量,对同一函数的其他调用无法更改它。谢谢您的回答。添加context
后,我丢失了data:{}
part中的变量。两者都使用有问题吗?没有。上下文
与数据
无关<代码>数据
是服务器返回的内容,上下文
与此无关。一定是其他问题。是的,我撤消了上次的更改并为您添加了代码,它可以正常工作。但问题出在另一个地方。谢谢