【发布时间】:2020-01-05 22:08:18
【问题描述】:
这个问题发生在 wordpress 主题上。简而言之,我之前遍历了一个 id 数组,并对每个 id 的外部 api 执行 wp_remote_get。它有效,但产生了页面加载问题,因此重构为使用 ajax,现在 wp_remote_get 仅适用于第一个数组项。以下是 API url 的结构示例:
http://example-api-url/is-available&id={id}
我的 PHP 文件有一个 foreach 循环,它为每个 id 执行 wp_remote_get。远程 get 被发送到 JS 文件,该文件返回该 ID 的 true 或 false。最终,我想返回一个从远程获取返回真实响应的 ID 数组。
现在我正在使用 Ajax 设置,api 调用似乎可以工作,但仅适用于数组中的第一个 ID。
我已经尝试将 id 数组发送到 JS 文件并在那里循环遍历它们,目的是返回新的 id 数组并返回一个真值。这里的问题在于 ajax url,将 &id= 参数添加到 ajaxUrl 一直返回 403 错误。
我还尝试将 check_test() 函数设置为将 ID 作为参数而不包含循环,然后设置第二个函数在循环中运行 check_test()。我不确定为什么使用 AJAX 进行远程获取仅适用于第一个数组项,而以前,remote_get 对每个项都有效。
在这个例子中,我预计会看到 4 条控制台日志消息,它们是真还是假;每个 ID 的响应,但我只看到一个。
我的下一个想法是尝试为每个数组项设置唯一的随机数,但不知道我是否在寻找正确的树。任何建议表示赞赏!
function check_test( ) {
if ( 1 !== wp_verify_nonce( $_GET['nonce'], 'check-test' ) ) {
status_header( 403 );
die( esc_html( get_status_header_desc( 403 ) ) );
}
$cache_key = 'check-test-' . wp_rand();
$data = get_transient( $cache_key );
$ids = [ '1234', '3215', '1110', '0191' ];
foreach ( $ids as $id ) :
$response = wp_remote_get( "http://example-api-url/is-available&id=
" . $id );
if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
$data = wp_remote_retrieve_body( $response );
} else {
$data = '';
}
set_transient( $cache_key, $data, HOUR_IN_SECONDS );
echo $data;
exit;
endforeach;
}
add_action( 'wp_ajax_check_test', 'check_test' );
add_action( 'wp_ajax_nopriv_check_test', 'check_test' );
这是 Javascript 文件的样子:
runCheck() {
const url = `${window.checkTest.ajaxUrl}?action=check_test&nonce=${window.checkTest.nonce}`;
return fetch(url)
.then((response) => {
if (response.ok) {
return response.text();
}
return false;
})
.then((data) => {
if ('true' === data) {
console.log('true');
} else if ('false' === data) {
console.log('false');
}
})
.catch((err) => {
if (console && console.error) { // eslint-disable-line no-console
console.error(err); // eslint-disable-line no-console
}
});
}
【问题讨论】:
标签: php ajax wordpress foreach fetch