首页 > 解决方案 > 从 API 响应中解析数据,调用函数直到收到参数

问题描述

我正在尝试使用 jQuery 调用 API。由于我是 jQuery 新手,因此我面临一些问题。

首先,我使用 PHP 从 URL 收到一封电子邮件,如下所示:<?php $email = $_GET['email']; ?>

然后我需要$email在下面的函数中传递值:

function jsCall() {
  var settings = {
    "url": "url to api",
    "method": "POST",
    "timeout": 0,
    "headers": {
      "Content-Type": "application/json"
    },
    // email is dynamic, should pass value from php
    "data": JSON.stringify({"email": "test@gmail.com"}),
  };

  $.ajax(settings).done(function(response) {
    console.log(response);
    var obj = (JSON.stringify(response));

    //get code, if code is empty call function again in 35 sec
    var code = obj.code; //returns NULL
  });
}

当我 console.log(response) 时,我得到

data:Array(1)
  0:
    code:"12315135486132"

console.log(code)返回null

我需要jsCall()在页面加载后 30 秒调用。然后如果code是空的,我需要每 35 秒运行一次脚本。何时code有值我需要将页面重定向到final.php?code=(code_value)

第一次调用函数:

setTimeout(function() { jsCall() }, 8000);  

标签: javascriptjquery

解决方案


您应该注意的第一个问题是,鉴于您显示的控制台输出,您应该使用它response[0].code来访问该值,因为对请求的响应是一个对象数组。对其进行字符串化不是必需的,并且会导致您尝试访问属性的方式出现问题。

其次,您需要的只是ifAJAX 回调中的一个条件,以便重定向或设置计时器以再次进行 AJAX 调用。尝试这个:

function jsCall() {
  var settings = {
    "url": "url to api",
    "method": "POST",
    "timeout": 0,
    "headers": {
      "Content-Type": "application/json"
    },
    "data": JSON.stringify({ "email": "<?= $email ?>" }),
  };

  $.ajax(settings).done(function(response) {
    let code = response.data[0].code;
    if (code) {
      window.location.assign('final.php?code=' + code);
    } else {
      setTimeout(jsCall, 35000); // make AJAX call again in 35 seconds
    }
  });
}

setTimeout(jsCall, 30000); // call 30 seconds after loading

推荐阅读