[英]How can I pass parameters to a jQuery $.getJSON callback method?
我正在尝试使用 jQuery 通过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
。 这是因为回调的方法签名是:
callback(data, textStatus) 请求成功时执行的回调函数。
如何将 1 个或多个参数传递给回调方法?
扭曲函数,例如
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)
});
您可以使用.ajax方法:
var locationType = 3;
var url = 'blah blah blah' + '&locationType=' + locationType;
$.ajax({
url: url,
context: { lt: locationType },
success: function(results) {
searchResults(results, this.lt);
}
});
可以试试:
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.