Wordpress排队jquery无法正常工作

时间:2018-04-09 20:18:10

标签: javascript php jquery wordpress

我在当前的干净wordpress安装上安装了一个插件。但是,只要插件的小部件被拉上

,我总会得到以下错误
if (!is_admin()) {

function woocommerce_ogonecw_add_frontend_css() {
    wp_register_style('woocommerce_ogonecw_frontend_styles', plugins_url('resources/css/frontend.css', __FILE__));
    wp_enqueue_style('woocommerce_ogonecw_frontend_styles');
    true);

    wp_register_script('ogonecw_frontend_script', plugins_url('resources/js/frontend.js', __FILE__), array(
        'jquery'
    ));

    wp_enqueue_script('ogonecw_frontend_script');
    wp_localize_script('ogonecw_frontend_script', 'woocommerce_ogonecw_ajax',
        array(
            'ajax_url' => admin_url('admin-ajax.php')
        ));
}
add_action('wp_enqueue_scripts', 'woocommerce_ogonecw_add_frontend_css');

我检查了js文件中的插件,他们似乎都正确使用了jQuery而不是$也是register_script函数需要jquery作为依赖

下面你可以看到add_action函数

jQuery(function (jQuery) {

var isSubmitted = false;

var CheckoutObject = {

    cssClass: '',
    successCallback: '',

    placeOrder: function() {
        var form = jQuery('form.checkout');

        var form_data = form.data();

        // WGM: Back Button
        if(jQuery("input[name=cw-wgm-button-back]").length > 0) {
            return true;
        }
        //WGM: MultiStep
        if(jQuery("input[name=wc_gzdp_step_submit]").length > 0) {
            if(jQuery("input[name=wc_gzdp_step_submit]").val() == "address"){
                return true;
            }
        }

        var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
        var selectedPaymentMethod = selectedPaymentMethodElement.val();
        var secondRun = false;
        if(jQuery("input[name=ogonecw_payment_method_choice]").length > 0) {
            secondRun = true;
            selectedPaymentMethodElement = jQuery("input[name=ogonecw_payment_method_choice]");
            selectedPaymentMethod = selectedPaymentMethodElement.val();

        }
        var moduleName = 'ogonecw';
        var selectedModuleName = (selectedPaymentMethod != undefined) ?
                selectedPaymentMethod.toLowerCase().substring(0, moduleName.length) : '';

        onOgoneCwCheckoutPlaceObject = this;

        if (moduleName == selectedModuleName) {
            form.addClass('processing');
            if ( form_data["blockUI.isBlocked"] != 1 ) {
                form.block({
                    message: null,
                    overlayCSS: {
                        background: '#fff',
                        opacity: 0.6
                    }
                });
            }

            this.successCallback = previewAuthorization;
            this.cssClass = 'ogonecw-preview-fields';
            onOgoneCwCheckoutPlaceObject = this;

            if(secondRun) {
                this.generateOrder(form, selectedPaymentMethod);
                return false;
            }

            var validateFunctionName = 'cwValidateFields'+selectedPaymentMethod.toLowerCase();
            var validateFunction = window[validateFunctionName];

            if (typeof validateFunction != 'undefined') {
                validateFunction(function(valid){onOgoneCwCheckoutPlaceObject.successCall();}, function(errors, valid){onOgoneCwCheckoutPlaceObject.failureCall(errors, valid);});
                return false;
            }
            onOgoneCwCheckoutPlaceObject.successCall();

            return false;
        }

    },

    failureCall: function(errors, valid){
        alert(errors[Object.keys(errors)[0]]);
        var form = jQuery('form.checkout');
        form.removeClass('processing').unblock();
        form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
    },

    successCall : function(){

        var form = jQuery('form.checkout');
        var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
        var selectedPaymentMethod = selectedPaymentMethodElement.val();

        onOgoneCwCheckoutPlaceObject = this;

        if(selectedPaymentMethodElement.parents('li').find('.ogonecw-validate').length > 0){

            var ajaxUrl;
            if(typeof wc_checkout_params != 'undefined') {
                ajaxUrl = wc_checkout_params.ajax_url;
            }
            if(typeof checkoutUrl == 'undefined') {
                ajaxUrl = woocommerce_params.ajax_url;
            }                   
            var separator = ajaxUrl.indexOf('?') !== -1 ? "&" : "?";
            ajaxUrl = ajaxUrl+separator+"action=woocommerce_ogonecw_validate_payment_form";

            var inputData = getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase());
            var postData = "&";
            jQuery.each(inputData, function(key, value) {
                postData += encodeURIComponent(key)+"="+encodeURIComponent(value)+"&";
            });
            jQuery.ajax({
                type:       'POST',
                url:        ajaxUrl,
                data:       form.serialize()+postData+ onOgoneCwCheckoutPlaceObject.cssClass + "=true",
                success:    function( code ) {
                    var response = '';
                    try {
                        response = jQuery.parseJSON(code);
                        if ( response.result == 'success' ) {
                            onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
                            return false;
                        }
                        else if ( response.result == 'failure' ) {
                            throw 'Result failure';
                        } else {
                            throw 'Invalid response';
                        }
                    }
                    catch(err ){
                        // Remove old errors
                        jQuery( '.woocommerce-error, .woocommerce-message' ).remove();

                        // Add new errors
                        if ( response.message ) {
                            form.prepend(response.message);
                        } else {
                            form.prepend(code);
                        }

                        // Cancel processing
                        form.removeClass( 'processing' ).unblock();

                        // Lose focus for all fields
                        form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();

                        // Scroll to top
                        jQuery( 'html, body' ).animate({
                            scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
                        }, 1000 );

                    }
                },
                dataType: 'html'

            });
            return false;
        }
        else {              
            onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
            return false;
        }

    },

    generateOrder: function(form, selectedPaymentMethod) {

        onOgoneCwCheckoutPlaceObject = this;

        var checkoutUrl;
        if(typeof wc_checkout_params != 'undefined') {
            checkoutUrl = wc_checkout_params.checkout_url;
        }
        if(typeof checkoutUrl == 'undefined') {
            checkoutUrl = woocommerce_params.checkout_url;
        }

        jQuery.ajax({
            type:       'POST',
            url:        checkoutUrl,
            data:       form.serialize() + "&" + onOgoneCwCheckoutPlaceObject.cssClass + "=true",
            success:    function( code ) {
                var response = '';
                try {
                    if (code.indexOf("<!--WC_START-->") >= 0) {
                        code = code.split("<!--WC_START-->")[1];
                    }
                    if (code.indexOf("<!--WC_END-->") >= 0) {
                        code = code.split("<!--WC_END-->")[0];
                    }

                    try {
                        // Check for valid JSON
                        response = jQuery.parseJSON( code );
                    } catch ( e ) {
                        // Attempt to fix the malformed JSON
                        var validJson = code.match( /{"result.*"}/ );
                        if ( null === validJson ) {
                            throw 'Invalid response';
                        } else {
                            response = jQuery.parseJSON(validJson[0]);
                        }
                    }                                               

                    if ( response.result == 'success' ) {
                        onOgoneCwCheckoutPlaceObject.successCallback(response, selectedPaymentMethod);
                    }
                    else if ( response.result == 'failure' ) {
                        throw 'Result failure';
                    } else {
                        throw 'Invalid response';
                    }
                }
                catch( err ) {

                    if ( response.reload === 'true' ) {
                        window.location.reload();
                        return;
                    }

                    // Remove old errors
                    jQuery( '.woocommerce-error, .woocommerce-message' ).remove();

                    // Add new errors
                    if ( response.messages ) {
                        form.prepend( response.messages );
                    } else {
                        form.prepend( code );
                    }

                    // Cancel processing
                    form.removeClass( 'processing' ).unblock();

                    // Lose focus for all fields
                    form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();

                    // Scroll to top
                    jQuery( 'html, body' ).animate({
                        scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
                    }, 1000 );

                    // Trigger update in case we need a fresh nonce
                    if ( response.refresh === 'true' ) {
                        jQuery( 'body' ).trigger( 'update_checkout' );
                    }

                    jQuery( 'body' ).trigger( 'checkout_error' );
                }
            },
            dataType: 'html'

        });
    },
};


var getFormFieldValues = function(parentCssClass, paymentMethodPrefix) {
    var output = {};
    jQuery('.' + parentCssClass + ' *[data-field-name]').each(function (element) {
        var name = jQuery(this).attr('data-field-name');
        if(name.lastIndexOf(paymentMethodPrefix, 0) === 0) {
            name = name.substring(paymentMethodPrefix.length);
            name = name.substring(1, name.length -1 );
            if(this.type == "radio") {
                 if(this.checked) {
                     output[name] = jQuery(this).val();
                 }
            }
            else{
                output[name] = jQuery(this).val();
            }

        }
    });

    return output;
};

var generateHiddenFields = function(data) {
    var output = '';
    jQuery.each(data, function(key, value) {
        output += '<input type="hidden" name="' + key + '" value="' + value + '" />';
    });

    return output;
};


var removeNameAttributes= function(cssClass) {
    // Remove name attribute to prevent submitting the data
    jQuery('.' + cssClass + ' *[name]').each(function (element) {
        jQuery(this).attr('data-field-name', jQuery(this).attr('name'));
        if(jQuery(this).is(':radio')){
            return true;
        }
        jQuery(this).removeAttr('name');
    });

}

var addAlias = function(cssClass){

    // Add listener for alias Transaction selector
    jQuery('.' + cssClass).parents('li').find('.ogonecw-alias-input-box > select').bind('change', function() {
        jQuery('body').trigger('update_checkout');
    });

}


var registerCheckoutObject = function(){
    bindOrderConfirmEvent(CheckoutObject);
};


var bindOrderConfirmEvent = function (CheckoutObject) {
    var form = jQuery('form.checkout');
    var attached = form.attr('data-ogonecw-attached');
    if (attached != 'true') {
        form.attr('data-ogonecw-attached', 'true');
        form.bind('checkout_place_order', function() {
            return CheckoutObject.placeOrder();
        });
        return false;
    }
};




// We have to make sure that the JS in the response is executed.
jQuery( document ).ready(function() {
    if (typeof window['force_js_execution_on_form_update_listener'] === 'undefined') {
        window['force_js_execution_on_form_update_listener'] = true;
        jQuery('body').bind('updated_checkout', function() {
            removeNameAttributes('ogonecw-preview-fields');
            addAlias('ogonecw-preview-fields');
            if (jQuery('.ogonecw-preview-fields').length > 0) {         
                registerCheckoutObject();
            }
        });
    }
});


jQuery( document ).ajaxStop(function(event, xhr, settings) {
    removeNameAttributes('ogonecw-preview-fields');
    addAlias('ogonecw-preview-fields');
    if (jQuery('.ogonecw-preview-fields').length > 0) {         
        registerCheckoutObject();
    }
});

var previewAuthorization = function (result, selectedPaymentMethod) {
    if(typeof result.redirect !== 'undefined') {

        var additionalFields = jQuery('<div class="ogonecw-preview-fields" style="display: none;"></div>');
        jQuery('.' + 'ogonecw-preview-fields' + ' *[data-field-name]').each(function (element) {

            var name = jQuery(this).attr('data-field-name');
            if(name.lastIndexOf(selectedPaymentMethod.toLowerCase(), 0) === 0) {
                jQuery(additionalFields).append(jQuery(this));
            }

        });
        var redirectUrl;
        if ( result.redirect.indexOf( "https://" ) != -1 || result.redirect.indexOf( "http://" ) != -1 ) {
            redirectUrl = result.redirect;
        } else {
            redirectUrl = decodeURI( result.redirect );
        }

        jQuery.get(redirectUrl, function(data){
            var newBodyString = data.replace(/^[\S\s]*<body[^>]*?>/i, "").replace(/<\/body[\S\s]*jQuery/i, "");
            var newBody = jQuery("<div></div>").html(newBodyString);
            if(newBody.find('.wgm-go-back-button').length > 0){
                jQuery('body').html(newBody.html());
                jQuery('form.checkout').append(additionalFields);
                jQuery('form.checkout').append('<input type="hidden" name="ogonecw_payment_method_choice" value="'+selectedPaymentMethod+'"/>');
                jQuery('.wgm-go-back-button').on('click', function() {
                    jQuery('form.checkout').append('<input type="hidden" name="cw-wgm-button-back" value="back"/>');
                });

                jQuery('form.checkout').on('submit', function(){
                    return CheckoutObject.placeOrder();
                });
                jQuery("html, body").animate({
                    scrollTop: jQuery("form.checkout").offset().top - 100
                }, 1e3);
            }
            else {
                window.location = decodeURI( redirectUrl );
            }

        });
    }

    else if(typeof result.ajaxScriptUrl !== 'undefined'){
        jQuery.getScript(result.ajaxScriptUrl, function() {
            eval("var callbackFunction = " + result.submitCallbackFunction);
            callbackFunction(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
        });
    }
    else {
        var newForm = '<form id="ogonecw_preview_form" action="' + result.form_action_url + '" method="POST">';
        newForm += result.hidden_form_fields;
        newForm += generateHiddenFields(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
        newForm += '</form>';
        jQuery('body').append(newForm);
        jQuery('#ogonecw_preview_form').submit();
    }
}

frontend.js看起来像这样

{{1}}

});

那么究竟是什么造成了这个错误,因为插件似乎设置正确

0 个答案:

没有答案