for循环中的Ajax POST请求在第二次迭代期间影响POST数据

时间:2018-11-14 10:46:56

标签: javascript arrays ajax wordpress async-await

我正在for循环中发送ajax请求,这就是我的循环的工作方式:

let postDbData = async ($, ajaxUrl) =>{
  for( let page_num = 1; page_num > 0; page_num++ ){
    let imageData = []; //1. Define an empty Array
    await dbData($, ajaxUrl, page_num).then( i => imageData = i );
     //2. Calls dbData() which returns an array. Assign that that returned array to imageData
    console.log(imageData); 
    await $.post( ajaxUrl, { action: "insert_sync_data_db", imageData: imageData } ) 
     //3. Send imageData to server Using POST request, to save it into database
    if(imageData.length <= 0) page_num = 0; 
     // 4. if dbData() does'nt return an array or return an blank array, set page_num to 0 so we can get out from the loop
  }
}

dbData()在每次迭代中都返回唯一的数组。我想做的是,在每次迭代中都将imageData数组替换为新数组,但是我的代码不是替换先前的内容,而是将新数据推送到imageData中。

问题发生在第二次迭代中,数组imageData保留了先前迭代的值(就像忽略了let imageData = [];一样)。但是,这是不可能的。

当我对Ajax POST请求发表评论时,数组停止保留以前的值。删除发布请求后,我的imgData变量的先前值在每次迭代中都被刷新,新值出现在imgData//await $.post( ajaxUrl, { action: "insert_sync_data_db", imageData: imageData } ))中 我不知道为什么这个Ajax请求弄乱了我的Array。

此功能依赖的其他功能。

dbData()

let dbData = async ($, ajaxUrl, page_num) => {

    let data = [];

    await compareImagesToSync($, ajaxUrl, page_num).then( async i => {
        await getImageDetails(i).then( i => {
            i.data.data.forEach( i => {
                let temp = {};
                temp.id = i.id;
                temp.preview_url = i.assets.preview.url;
                temp.description = i.description;
                temp.keywords = i.keywords.join(", ");
                data.push(temp);
            } );
        } );
    } );

    return await data;
}

compareImagesToSync()

let compareImagesToSync = async ($, ajaxUrl, page_num) => {

    let fetchImagesFromDB = async ($, ajaxUrl) => await $.post(ajaxUrl, { action: "get_images_from_db" });

    let fetchImagesFromAPI = async () => await getLicensedImages(page_num, 2);

    let request = async () => await axios.all([fetchImagesFromDB($, ajaxUrl), fetchImagesFromAPI()])
    .then(axios.spread( (db, api) => {
        let dbImages = JSON.parse(db);
        return diffArray(dbImages, api);
    } ))
    .catch(e => console.log(e));

    return await request();
}

getImageDetails()

let getImageDetails = async ( image_id = null ) => {

    if(image_id == null || image_id == "" || image_id.length <= 0) return;

    image_id = image_id.map( v => `id=${v}` ).join('&')

    const APIURL = `https://api.shutterstock.com/v2/images?${image_id}&view=full`;

    const request = async () => await axios.get(APIURL, { headers: auth_header() } );

    return await request();
}

diffArray()

let diffArray = (arr1, arr2) => {

  var newArr = [];

  arr1.map(val => arr2.indexOf(val) < 0 ? newArr.push(val) : '');

  arr2.map(val => arr1.indexOf(val) < 0 ? newArr.push(val) : '');

  return newArr;

}

这里是处理Ajax请求的PHP函数。这可能与我的问题无关,但仍在添加此代码,以更好地理解我的代码:

add_action( 'wp_ajax_insert_sync_data_db', 'create_shutterstock_image_post' );
add_action( 'wp_ajax_nopriv_insert_sync_data_db', 'create_shutterstock_image_post' );
function create_shutterstock_image_post(){

    ini_set('max_execution_time', 600);
    foreach ($_POST["imageData"] as $value) {
        $postarr = array(
            "post_content" => $value['keywords'],
            "post_title" => $value['description'],
            "post_excerpt" => $value['description'],
            "post_status" => "publish",
            "post_type" => "portfolio",
            "guid" => $value['id'],
            "post_name" => $value['id'],
            "meta_input" => array(
                '_bk_portfolio_thumbnail_behavior' => 'content_link', 
                '_bk_page_builder_item_size_combobox' => 'one_one',
                '_bk_page_builder_items_combobox' => 'bk_accordion',
                '_bk_page_layout' => 'fixed_centered',
                '_bk_fixed_page_width' => '1024',
                '_bk_page_fullscreen_background_content', 'bk-none'
            )
        );
        $postID = wp_insert_post($postarr, true);

        Generate_Featured_Image($value['preview_url'], $postID);
    }
    wp_die();
}

处理compareImagesToSync()发送的请求的功能

add_action( 'wp_ajax_get_images_from_db', 'get_images_from_db' );
add_action( 'wp_ajax_nopriv_get_images_from_db', 'get_images_from_db' );
function get_images_from_db(){
    ini_set('max_execution_time', 1000);
    $image_ids = array();
    $query = new WP_Query(array("post_type" => "portfolio", "posts_per_page" => "-1", "post_status" => "publish"));

    if($query->have_posts()){
        while ($query->have_posts()) {
            $query->the_post();
            $image_ids[] = basename( get_permalink() ); 
        }
    }

    echo json_encode($image_ids);

    wp_die();
}

Generate_Featured_Image()

function Generate_Featured_Image( $image_url, $post_id  ){
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
    $file = (wp_mkdir_p($upload_dir['path'])) ? $upload_dir['path'] . '/' . $filename : $upload_dir['basedir'] . '/' . $filename;
    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
    $res2= set_post_thumbnail( $post_id, $attach_id );

    return (!$res1 || !$res2) ? false : true;


}

0 个答案:

没有答案