为什么运行时下面不起作用。我试图在脚本1 中声明一个变量我认为定义外部变量会使它成为全局变量。我会说这是一个chrome应用程序,我在我的清单中有必要的权限,我在我的HTML中有Jquery的正确脚本。
var userName;`
然后在脚本2 `
中使用它 var text = 'Hello' + userName + 'This is a test'`
完整代码
脚本1
var userName;
var userEmail;
var userTeamName;
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
var authorizationToken = "xxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Address').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return myapiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
jsonData = data.user.name;
of the function
})
.then(function(data) {
userName = data.user.name;
userEmail = data.user.email;
userTeamName = data.user.teams[0].name;
})
脚本2
$(document).ready(function() {
$('#contact-submit').on('click', function(e) {
e.preventDefault();
var btn = $(e.target);
btn.attr("disabled", "disabled"); // disable button
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'Hello' + userName + 'This is a test'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});