【问题标题】:Http Requests within each other (variable issue)彼此内部的 Http 请求(可变问题)
【发布时间】: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 不客气 :) 请将我的答案标记为正确答案。

标签: jquery json api


【解决方案1】:

你应该改变这一行:

xhr.send("{\n \"utoken\": \"response.access_token\"\n}");

对此:

xhr.send("{\n \"utoken\": \"" + response.access_token + "\"\n}"); // Added additional quotes for response.access_token

原因是您将 response.access_token 变量作为字符串发送,但应该作为变量用引号括起来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    相关资源
    最近更新 更多