我可以通过只使用jQuery的WooCommerce api来解决这个问题。
$(".check-zip").on(\'click\', function () {
var zipCode = jQuery("#custom_zip").val();
var zipArray = [];
var url = WPURLS.template_url;
$(".zip-msg").remove();
$.ajax({
type: \'GET\',
url: url + \'/wp-json/wc/v2/shipping/zones/1/locations\',
dataType: "json",
data: {
type: \'postcode\'
},
beforeSend: function (xhr) {
xhr.setRequestHeader(\'X-WP-Nonce\', wpApiSettings.nonce);
},
success: function (data) {
$.each(data, function (key, value) {
zipArray.push(value.code);
}); //end each function
if ($.inArray(zipCode, zipArray) > -1) {
$("#custom_zip_checkout_field").append("<div class=\'zip-msg\'>Service is available at " + zipCode + "</div>");
} else {
$("#custom_zip_checkout_field").append("<div class=\'zip-msg\'>Oops! We are not currently servicing your area.</div>");
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
}); //end ajax function
});
if($.inArray(zipCode, zipArray) > -1 ) {
jQuery("#custom_zip_checkout_field").append("<div class=\'zip-msg\'>Service is available at " + zipCode + "</div>");
}else{
jQuery("#custom_zip_checkout_field").append("<div class=\'zip-msg\'>Oops! We are not currently servicing your area.</div>");
}
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log( jqXHR, textStatus, errorThrown );
}
});//end ajax function
});