如何將腳本1,Name, Email, Teams
的結果轉換爲我可以使用的變量腳本2?在一個腳本中創建變量並在另一個腳本中使用。 JQuery/HTML/JS
我正在做一個API調用來獲取一些JSON然後我想要使用某些值作爲消息中的文本然後我發送到鬆弛。
示例。
$('.Name').html(data.user.name); // Returns John
$('.Email').html(data.user.email); // Returns [email protected]
$('.Teams').html(data.user.teams[0].name); // Returns JohnsTeam
var text = 'Hello my name is $Name + my email is $Email + From $Teams'
輸出=你好,我的名字是約翰我的電子郵件是[email protected]從JohnsTeam
腳本1
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 = "xxxxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').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)
})
腳本2
$(document).ready(function(){
$('#contact-submit').on('click',function(e){
e.preventDefault();
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'This is a message'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text // What I want to dynamically change
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});
感謝您的回覆,雖然我不確定您的意思,但是不要假設您可以提供示例?謝謝 –