简体   繁体   English

WordPress:在每个循环中遍历多个api获取。 仅返回第一个数组项的响应

[英]Wordpress: Iterate through multiple api fetches within for each loop. Only returns response for first array item

This issue is happening on a wordpress theme. 此问题发生在wordpress主题上。 In short, I previously was iterating through an array of id's and doing a wp_remote_get to an external api for each id. 简而言之,我以前遍历一个id数组,并为每个id对外部api做wp_remote_get。 It worked but created page load issues, so refactoring to use ajax and now the wp_remote_get only works on first array item. 它起作用了,但是却造成了页面加载问题,因此重构为使用ajax,现在wp_remote_get仅适用于第一个数组项。 Here's an example of how the API url is structured: http://example-api-url/is-available&id={id} 以下是API网址的结构http://example-api-url/is-available&id={id}http://example-api-url/is-available&id={id}

My PHP file has a foreach loop that does a wp_remote_get for each id. 我的PHP文件有一个foreach循环,该循环对每个ID进行wp_remote_get。 The remote get is sent to the JS file, which returns a true or false for that ID. 远程获取将发送到JS文件,该文件对该ID返回true或false。 Ultimately, I'd like to return an array of ID's that return a true response from the remote fetch. 最终,我想返回一个ID数组,该数组返回来自远程提取的真实响应。

Now that I'm using the Ajax set up, the api call seems to work, but only on the first ID in the array. 既然我正在使用Ajax设置,那么api调用似乎可以正常运行,但仅在数组中的第一个ID上有效。

I've tried sending the array of id's to the JS file and looping through them there with the intention of returning the new array of id's returning a true value. 我试过将ID数组发送到JS文件,并在其中循环遍历,目的是返回ID为true的新数组。 The problem here was with the ajax url, adding the &id= parameter to the ajaxUrl kept returning 403 errors. 这里的问题是ajax网址,将&id =参数添加到ajaxUrl中,始终返回403错误。

I've also tried having the check_test() function set up to take an ID as a parameter and not include a loop, then set up a second function that runs check_test() within a loop. 我还尝试过设置check_test()函数以将ID作为参数而不包含循环,然后设置第二个在循环内运行check_test()的函数。 I'm not sure why doing a remote get using AJAX only works on the first array item, where previously, the remote_get worked on each item. 我不确定为什么使用AJAX进行远程获取仅适用于第一个数组项目,而以前,remote_get适用于每个项目。

In this example, I'm expecting to see 4 console log messages of true or false; 在此示例中,我希望看到4个控制台日志消息,它们是对还是错。 the response for each ID, but I'm only seeing one. 每个ID的响应,但我只看到一个。

My next idea was to try to set up unique nonces for each array item, but don't know if I'm barking up the right tree. 我的下一个想法是尝试为每个数组项设置唯一的随机数,但是不知道我是否在树正确的树。 Any advice is appreciated! 任何建议表示赞赏!

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' );

This is what the Javascript file looks like: 这是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
        }
      });
  }

Ugh, while refactoring, I had accidentally added my endforeach; gh,在重构时,我不小心添加了我的努力。 AFTER the exit; 出口后; Helps to access the whole array when you don't exit early :( 当您不早退出时,有助于访问整个数组:(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法遍历类别循环内的帖子。 仅获得第一项 - Can't loop through posts inside a category loop. Only get the first item ajax调用仅显示每个循环中第一项的输入值。 需要它显示取决于按钮单击的上下文 - ajax call only showing input values for the first item in for each loop. Need it to display depending on context of button click Laravel Seeder - 在for循环中迭代数组 - Laravel Seeder - iterate through an array within a for loop PHP foreach循环仅返回第一项 - PHP foreach loop only returns the first item 我如何使用 for each 循环从命名数组返回信息。 WordPress插件 - how do i return the info from the named array with a for each loop. WordPress-Plugin 如何遍历此循环分别获取每个项目 - How do I iterate through this loop Get each Item Separately PHP for循环在for循环内。 尝试对多个数组列求和以获得组合 - PHP for loop within for loop. Trying to sum multiple array columns to get combinations PHP遍历li列表并为数组中的每个项目放置值进行迭代 - PHP Iterate Through li List & For Each Item Put Value in Array 如何遍历每个数组项并插入到数据库 - How to iterate through each array item and insert to database PHP PDO-增量for循环,每个循环获取下一个数组行 - PHP PDO - incremental for loop that fetches the next array row with each loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM