You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AJAX异步请求中custPhone与custToken变量Undefined问题求助

解决AJAX异步调用中变量传递导致Undefined的问题

我是AJAX初学者,目前从两个不同端点分别获取手机号和令牌数据,已成功获取且控制台可打印,但在sso函数中使用custPhone和custToken时变量返回Undefined值,恳请帮助解决该问题。

相关代码如下:

const button = document.getElementById('btn-submit');
button.addEventListener('click',function() {
  
  const email = document.getElementById('CustomerEmail').value; 
  
   function sso(url, custPhone, custToken, callback) {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", url);

      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.setRequestHeader("Authorization", `Bearer ${custToken}`);
      var data = `{
          "phone_number": ${custPhone},
          "countryCode": "ID",
          "programId": "4002203192624"
      }`;

      xhr.onreadystatechange = function () {
         if (xhr.readyState === 4) {
            console.log(xhr.status);
            const value3 = JSON.parse(xhr.response);
            const SSO = value3.url; 
            callback(SSO);
         }};

      xhr.send(data);
  }
  
  
  function getPhoneNumber(url, callback) {
    // GET CUST DETAIL BY EMAIL
    const email = document.getElementById('CustomerEmail').value;

    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);

    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("X-Shopify-Access-Token", "shppa_8key");

    xhr.onreadystatechange = function() {
       if (xhr.readyState === 4) {
          const value1    = JSON.parse(xhr.response);
          const custPhone = value1.customers[0].phone;
          callback(custPhone);
       }};
  
    xhr.send();
  }
  
  function getTokenCust(url, callback) {
      var xhr = new XMLHttpRequest();
    
      xhr.open("POST", url);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.setRequestHeader("Authorization", "Basic aWY5b0IwZHFZQTZzcHFpMGR3ajF0VnI3cTp2djhmRGJ5WTNVZHB6amtYSXd3dEZ2bVNUSkVKcE5scHp4VjJpUWxrbWt4VzJ3VTlzRg==");

      xhr.onreadystatechange = function () {
         if (xhr.readyState === 4) {
            const value2 = JSON.parse(xhr.response);
            const custToken = value2.access_token;
            callback(custToken);
         }};

      var data = `{
        "username": "98080001",
        "password": "0001",
        "grant_type": "password",
        "scope": "offline_access"
      }`;

      xhr.send(data);
  }
  
  getPhoneNumber(`https://zone-group-store.myshopify.com/admin/api/2021-07/customers/search.json?query=email:${email}`, function(custPhone){
    getTokenCust('https://api.gift.id/v1/pos/token', function(custToken){
      sso('https://api.gift.id/v1/pos/sso/wallet', custPhone, custToken, function(sso){
          alert(sso);
      });
    });
  });

问题分析与解决方案

核心问题排查

  1. JSON格式错误:sso函数中拼接phone_number时未给custPhone加引号,若手机号为字符串类型(如带区号),会直接破坏JSON语法,导致后端请求失败,进而引发后续变量异常。
  2. 缺少请求状态与数据有效性检查:当前代码仅判断readyState ===4,未验证HTTP响应状态码(如200)和返回数据的完整性,若请求失败或返回数据结构异常,会导致custPhone/custToken未正确赋值。

修复步骤

  1. 修复JSON数据格式:给phone_number的值添加引号,确保JSON语法合法:
var data = `{
    "phone_number": "${custPhone}",
    "countryCode": "ID",
    "programId": "4002203192624"
}`;
  1. 添加请求状态与数据校验:在每个AJAX回调中增加状态码检查和数据存在性验证:
  • 修改getPhoneNumber函数:
xhr.onreadystatechange = function() {
   if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        const value1 = JSON.parse(xhr.response);
        // 检查客户数组是否存在且有数据
        if (value1.customers?.length > 0) {
          const custPhone = value1.customers[0].phone;
          callback(custPhone);
        } else {
          console.error("未找到匹配的客户数据");
          callback(null);
        }
      } else {
        console.error("获取手机号失败,状态码:", xhr.status);
        callback(null);
      }
   }
};
  • 修改getTokenCust函数:
xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        const value2 = JSON.parse(xhr.response);
        if (value2.access_token) {
          const custToken = value2.access_token;
          callback(custToken);
        } else {
          console.error("返回数据中无access_token字段");
          callback(null);
        }
      } else {
        console.error("获取令牌失败,状态码:", xhr.status);
        callback(null);
      }
   }
};
  • 修改sso函数:
xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      if (xhr.status === 200) {
        const value3 = JSON.parse(xhr.response);
        if (value3.url) {
          const SSO = value3.url; 
          callback(SSO);
        } else {
          console.error("返回数据中无url字段");
          callback(null);
        }
      } else {
        console.error("SSO请求失败,状态码:", xhr.status);
        callback(null);
      }
   }
};
  1. 调用时增加变量有效性判断:在嵌套调用中检查custPhone和custToken是否有效,避免传递Undefined值:
getPhoneNumber(`https://zone-group-store.myshopify.com/admin/api/2021-07/customers/search.json?query=email:${email}`, function(custPhone){
  if (!custPhone) {
    alert("获取手机号失败,请检查邮箱是否正确");
    return;
  }
  getTokenCust('https://api.gift.id/v1/pos/token', function(custToken){
    if (!custToken) {
      alert("获取令牌失败,请稍后重试");
      return;
    }
    sso('https://api.gift.id/v1/pos/sso/wallet', custPhone, custToken, function(ssoUrl){
        if (ssoUrl) {
          alert(ssoUrl);
        } else {
          alert("SSO链接生成失败");
        }
    });
  });
});

内容的提问来源于stack exchange,提问作者icetoice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 08:03:56