javascript - 返回 GET 值并将其存储在 JS 中的变量中

标签 javascript jquery function get return

请注意,我是 JS 的新手,因此请期待您可能想象到的任何异常。

话虽这么说,我正在尝试在 JS 中创建一个函数。它由三个部分组成,但最终目标是用一些外部数据填充 select

第一个是 GET。在这里,我调用外部 API 来询问配置文件的总数。一切似乎都工作得很好,但每当我在函数外部执行 console.log(totalProfiles) 时,它的值似乎未定义。我尝试在末尾添加 return 但这不是解决方案。

var billingArray = [];
var billingProfiles = [];
var billingSelect = document.getElementById('billingSelect');
(function(){
    $.ajax({
        url: url,
        method: 'GET',
        crossDomain: true,
        withCredentials: true,
        dataType: 'JSON',
        headers: {
            'Authorization': 'Basic '+token,
        }
    })
    .done(function(response) { billingArray.push(response); var totalProfiles = billingArray[0]['total_count']; return totalProfiles; })
    .fail(function(jqXHR, textStatus, errorThrown) { console.log(textStatus); });
});

使用totalProfiles,我会调用相同的URL,这次将所有配置文件存储在一个数组中:

(function(totalProfiles){
    $.ajax({
        url: url+totalProfiles,
        method: 'GET',
        crossDomain: true,
        withCredentials: true,
        dataType: 'JSON',
        headers: {
            'Authorization': 'Basic '+token,
        }
    })
    .done(function(response) { billingProfiles.push(response); })
    .fail(function(jqXHR, textStatus, errorThrown) { console.log(textStatus); });
});

最后一部分包括通过 for 填充 select:

function(billingprofiles) {
    for (var i = 0; i < billingProfiles.length(); i++) {
        var billingProfileId = billingProfiles[i]["ngcp:billingprofiles"]["id"];
        var billingProfileName = billingProfile[i]["ngcp:billingprofiles"]["name"];

        var opt = document.createElement("option");
        opt.value() = billingProfileId;
        opt.textContent() = billingProfileName;
        dropdown.appendChild(opt);
    }
});

这里的问题是我不知道如何将totalProfiles从函数中取出,因此每当进程到达第二个时,就会由于变量未定义而失败。

这就是整个事情,你可以期待我之前谈到的那些异常现象。我认为这会起作用,但我开始怀疑我打算这样做的方式也可能是问题的一部分:

var billingArray = [];
var billingProfiles = [];
var billingSelect = document.getElementById('billingSelect');
var totalProfiles;

//Fetch total number of profiles
(function() {
  $.ajax({
    url: url,
    method: 'GET',
    crossDomain: true,
    withCredentials: true,
    dataType: 'JSON',
    headers: {
      'Authorization': 'Basic ' + token,
    }
  }).done(function(response) {
    billingArray.push(response);
    var totalProfiles = billingArray[0]['total_count'];
    return totalProfiles;
  }).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(textStatus);
  });
})().done(function(totalProfiles) {
  $.ajax({
    url: url + totalProfiles,
    method: 'GET',
    crossDomain: true,
    withCredentials: true,
    dataType: 'JSON',
    headers: {
      'Authorization': 'Basic ' + token,
    }
  }).done(function(response) {
    billingProfiles.push(response);
  }).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(textStatus);
  });
})().done(function(billingprofiles) {
  for (var i = 0; i < billingProfiles.length(); i++) {
    var billingProfileId = billingProfiles[i]["ngcp:billingprofiles"]["id"];
    var billingProfileName = billingProfile[i]["ngcp:billingprofiles"]["name"];

    var opt = document.createElement("option");
    opt.value() = billingProfileId;
    opt.textContent() = billingProfileName;
    billingSelect.appendChild(opt);
  }
}).fail(function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus);
});

一些注释可以更好地解释我这样做的内容和原因: 1. 在每个 .done 之前,我必须编写 () 以避免此错误

(intermediate value).done is not a function

  • 我现在遇到的错误发生在 .done(function(totalProfiles) {:
  • Uncaught TypeError: Cannot read property 'done' of undefined

    最佳答案

    您正在描述一系列串联的异步操作。 Promise 非常适合于此。从 ajax 获得的 Deferred 对象是一个 promise (现在),因此您可以通过从每个函数到下一个函数的返回链来实现:

    $.ajax({
        // ...
    })
    .then(billingArray => billingArray[0]['total_count']) // *** Return the count
    .then(totalProfiles => $.ajax({ // *** Return the promise for the billing profiles
         // ...options using `totalProfiles`...
    })
    .then(billingProfiles => {
        // ...use the billing profiles here
    })
    .catch(() => {
        // ...handle/report failure
    });
    

    请注意每个 then 处理程序如何转换通过它的内容,并且在它需要仅异步可用的信息的情况下,它会从 ajax 返回 promise ;结果将传递给下一个 then 处理程序。

    关于javascript - 返回 GET 值并将其存储在 JS 中的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60413374/

    相关文章:

    javascript - 只选择一个元素的子元素,由他的类标识

    javascript - fullCalendar - 禁用多选日

    javascript - Angular 6 event.stopPropagation() 在指令中不起作用(模板驱动形式已经采用 event.data)

    javascript - 单击 div 会触发 $ ('body' 的绑定(bind)。单击

    javascript - Codeigniter:由于tinymce文本区域而没有进行验证

    c - 如何定义此代码并将其作为函数调用?

    javascript - 在 map 循环中生成多个引用

    javascript - 如何对ajax返回数据的url进行编码然后附加到html?

    c - 使数组指向另一个数组的内存 C

    javascript - “if”语句无法正常运行