我想在WordPress中使用 AJAX 更改单击时的图像功能。下面是我的代码:
JS:
jQuery(".swatchinput label").click(function(){
var mycolor = jQuery(this).attr("data-option");
var postid = jQuery(".single-product .product.type-product").attr("data-id");
jQuery.ajax({
cache: false,
timeout: 8000,
url: php_array.admin_ajax,
type: "POST",
data: ({ action:'theme_post_vimage', colorimg: mycolor, postvalue: postid}),
beforeSend: function() {
},
success: function(response){
var myimageresponse = jQuery( response );
jQuery( '.product-image a img' ).attr('src', myimageresponse);
},
error: function( jqXHR, textStatus, errorThrown ){
console.log( 'The following error occured: ' + textStatus, errorThrown );
},
complete: function( jqXHR, textStatus ){
}
});
});
这是我的PHP/WordPress中的函数:
add_action('wp_ajax_theme_post_vimage','theme_post_vimage_init');
add_action( 'wp_ajax_nopriv_theme_post_vimage', 'theme_post_vimage_init' );
function theme_post_vimage_init() { ?>
<?php
global $post, $product, $woocommerce;
$postiID = $_POST['postvalue'];
$colorname = $_POST['colorimg'];
$product = new WC_Product_Variable( $postiID );
$variations = $product->get_available_variations();
foreach ( $variations as $variation ) {
if($variation['attributes']['attribute_pa_color'] == $colorname) :
$myimageurl = $variation['image']['url'];
echo $myimageurl;
endif;
}
?>
<?php }
当我单击我的颜色时,浏览器控制台中显示此错误:
Uncaught Error: Syntax error, unrecognized expression: http://samsonite.stuntmen.ae/wp-content/uploads/2017/05/PROD_COL_73353_1726_WHEEL-HANDLE-FULL.jpg
2条答案
按热度按时间uemypmqf1#
jQuery( response );
是错误的...为什么不直接使用response
?此外,我建议您将您实现更改为如下所示的内容。
PHP语言
jQuery查询器
查找
success
我做了更改。w1e3prcc2#
将第
data: ({ action:'theme_post_vimage', colorimg: mycolor, postvalue: postid}),
行替换为在你的 AJAX 输出中,你使用'?〉来放置不必要白色
更重要的是,
jQuery( response )
在您的成功函数中是什么?仅使用response
。