我正在尝试使用 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
来访问该值,因为对请求的响应是一个数组的物体。没有必要对其进行字符串化,并且会导致您尝试访问属性的方式出现问题。
其次,您只需要 AJAX 回调中的 if
条件即可重定向或设置计时器以再次进行 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
关于javascript - 解析API响应中的数据,调用函数直到收到参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61653116/