Javascript 如何将参数传递给jQuery$.getJSON回调方法?
我试图使用jQuery通过Javascript 如何将参数传递给jQuery$.getJSON回调方法?,javascript,jquery,callback,Javascript,Jquery,Callback,我试图使用jQuery通过Ajax/$.getJSON调用一些定制API 我试图将一个自定义值传递到Ajax回调方法中,但该值没有被传递,实际上被覆盖。这是我的代码: var locationType = 3; var url = 'blah blah blah' + '&locationType=' + locationType; $("#loading_status").show(); $.getJSON(url, null, function(results, location
Ajax/$.getJSON
调用一些定制API
我试图将一个自定义值传递到Ajax回调方法中,但该值没有被传递,实际上被覆盖。这是我的代码:
var locationType = 3;
var url = 'blah blah blah' + '&locationType=' + locationType;
$("#loading_status").show();
$.getJSON(url, null, function(results, locationType) {
searchResults(results, locationType)
});
在我使用AJAX调用URL之前,locationType
的值是3
。但是在调用成功返回数据后,locationType
的值现在是success
。这是因为:
回调(数据、文本状态)回调
如果
请求成功
如何向回调方法传递1个或多个参数?如果要在回调中使用
locationType
(其值为3
),只需使用
function(results) { .....
多亏了,
locationType将在回调中自动可用。在函数中扭曲,例如
function getResults(locationType) {
$.getJSON(url, null, function(results) {
searchResults(results, locationType)
});
}
但在您特定的情况下,您甚至不必传递它,您可以直接在回调中访问该值。您不需要传递它,只需引用您已有的变量,如下所示:
var locationType = 3;
var url = 'blah blah blah' + '&locationType=' + locationType;
$("#loading_status").show();
$.getJSON(url, null, function(results) {
searchResults(results, locationType)
});
此外,如果没有数据对象,则无需传递null
,这是一个可选参数,jQuery会检查第二个参数是否为函数,因此您可以执行以下操作:
$.getJSON(url, function(results) {
searchResults(results, locationType)
});
您可以使用以下方法:
可以尝试:
function getResults(locationType) {
$.getJSON(url, {p1:'xxx', p2: 'yyy'}, function(results) {
searchResults(results, locationType)
});
}
locationType变量是全局变量,所以您不需要将其作为参数,在一个极小的回调函数中,该变量是自由的,因此可以在周围环境中搜索,在本例中,该环境是全局环境。@jcubic-它不是全局变量(可能是,但可能不是),更准确地说,它在他关心的范围内可用。如果您正在执行循环并每次调用$.getJSON(),那么将其包装为函数将保留变量;否则,它将被覆盖。您必须小心此操作。对于固定值变量,这是有用的,但是如果您尝试这样做,例如,在locationType为索引的循环中,它在回调中的值将是回调执行时的值,而不是定义时的值。以防万一@DanibISHOP:那你怎么传递一个非固定值呢?如果你做了很多API调用,然后仍然需要知道哪个调用是从哪个ID加载的,那么非固定值可能是有用的。我相信上面的代码中有错误。当使用上下文设置时,“this”成为回调函数中的上下文,因此代码应该读取searchResults(results,this.lt);而不是searchResults(results,this.context.lt);。如果这个ajax调用被多次调用(可能在前一个调用返回之前),那么这是唯一正确的解决方案。
function getResults(locationType) {
$.getJSON(url, {p1:'xxx', p2: 'yyy'}, function(results) {
searchResults(results, locationType)
});
}
$.getJSON("url",
"//here you can define your id, secure key to check data in your console, if you don't have condition for id and secure key just remove the secure key part."
{secure_key:"noaccess"}, function(data){
console.log(data);
});