【发布时间】:2014-03-07 12:12:42
【问题描述】:
我有一个通过令牌调用的 http 请求,然后解析该令牌并在名为 response 的变量中使用。我想在 if 命令的下一个 http 请求中使用该变量。不幸的是,调用变量的正常方法不起作用。有人能指出我正确的方向吗?
我已经看到了响应,一切都非常完美。但是,变量 reponse 中的 utoken 没有读取输出。
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://yotpoapi.apiary.io/oauth/token');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (typeof cb !== "undefined") {
cb(this);
}
else {
var response = JSON.parse(this.responseText)
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://yotpoapi.apiary.io/apps/BLAHBLAH/purchases');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send("{\n \"utoken\": \"response.access_token\"\n}");
}
}
};
xhr.send("{\n \"client_id\": \"CLIENT ID\",\n \"client_secret\": \"CLIENT SECRET\",\n \"grant_type\": \"client_credentials\"\n}");
输出:
"utoken": "response.access_token",
预期输出:
"utoken": "123123213123123123123123123",
【问题讨论】:
-
我建议你看看
$.ajax()和JSON.stringify() -
输出似乎是硬编码的:xhr.send("{\n \"utoken\": \"response.access_token\"\n}")
-
@LarsJuelJensen 我们输入带有动态变量的 xhr.send。现在我们调用确保它的第一位是调用用户令牌。但是,我怎样才能将该用户令牌(存储在
response)带到下一个函数? -
你应该这样做:
xhr.send("{\n \"utoken\": \"" + response.access_token + "\"\n}"); -
@JSG 不客气 :) 请将我的答案标记为正确答案。