javascript - 从 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);
解决方案
您应该注意的第一个问题是,鉴于您显示的控制台输出,您应该使用它response[0].code
来访问该值,因为对请求的响应是一个对象数组。对其进行字符串化不是必需的,并且会导致您尝试访问属性的方式出现问题。
其次,您需要的只是if
AJAX 回调中的一个条件,以便重定向或设置计时器以再次进行 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
推荐阅读
- chart.js - Chart.js,如何减少标签和条形之间的空间(水平条形图)
- python - 某些模型无法加载 Django 自然键
- python - 如何使我的程序读取多个 txt 文件并将其创建为 python 的数据框?
- r - “光栅 IO 期间失败”可能与光栅大小有关?
- c++ - 更新到 VS2019 16.6 后无法将范围变换分配给向量
- javascript - 基本 +=1 函数,变量保存在 cookie 中
- javascript - 如果比较的值是真的,那么 $.getJSON()
- azure-logic-apps - 具有 O365 的逻辑应用程序 - 更改“回复”
- reactjs - 如何在 ReactJS 功能组件中触发子方法
- powershell - 在 PowerShell 脚本中添加函数