我有一个有 4 个参数的函数
function getToken(u, p, url, role) {
var that = this;
oururl = url;
$.ajax({
type: 'GET',
url: "/Base/getConfigUrl",
success: function (data) {
$.ajax({
type: 'GET',
async: false,
url: url + '?username=' + u + '&password=' + p,
success: 'callbackFunc',
error : 'callbackError',
contentType: "application/json",
dataType: 'jsonp'
});
}
});
以及回调函数
function callbackFunc(resultData) {
// how to get the outer parameter
}
在回调函数内部,我需要访问 Angular 色参数,我记录了 this
变量,但找不到任何内容
最佳答案
你本身不能。 role
变量在正确的范围内不存在。
您需要重构代码,以便可以从确实存在的位置获取变量并将其传递给callbackFunc 函数。
请参阅代码内嵌的注释,了解所有更改的说明。
function callbackFunc(resultData, role) {
// Edit the argument list above to accept the role as an additional argument
}
function getToken(u, p, url, role) {
var that = this;
var oururl = url; // Best practise: Make this a local variable. Avoid globals.
$.ajax({
type: 'GET',
url: "/Base/getConfigUrl",
success: function(data) {
$.ajax({
type: 'GET',
// async: false, // Remove this. You are making a JSONP request. You can't make it synchronous.
url: url;
data: { // Pass data using an object to let jQuery properly escape it. Don't mash it together into the URL with string concatenation.
username: u,
password: p
},
success: function(data) { // Use a function, not a string
callbackFunc(data, role); // Call your function here. Pass the role (and the data) as arguments.
},
error: function() {}, // Use a function, not a string
// contentType: "application/json", // Remove this. You are making a JSONP request. You can't set a content type request header. There isn't a request body to describe the content type of anyway.
dataType: 'jsonp'
});
}
});
关于javascript - 访问ajax外部参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44138632/