javascript - 用于翻译 Ajax 加载内容的 Transposh 插件

标签 javascript wordpress translation

我正在尝试让 transposh 插件 在每次购物车动态更新时进行翻译。目前,该插件将进行翻译,然后 woocommerce 将更新购物车,从而翻译消失。

我在 WooCommerce 的 checkout.js 中找到了以下代码:

    // Event for updating the checkout
    $('body').bind('update_checkout', function() {
        clearTimeout(updateTimer);
        update_checkout();
});

我相信这是 transposh 如何在 transposh.js 中进行翻译的代码(我只能找到它的缩小版):

(function(c){function D(b,a){if(0!==c.trim(a).length){var d=function(){var b=c(this).attr("id").substr(c(this).attr("id").lastIndexOf("_")+1),a=c("#"+e+"img_"+b);c("#"+e+b).attr("data-source",1);a.removeClass("tr-icon-yellow").removeClass("tr-icon-green").addClass("tr-icon-yellow")};c("*[data-token='"+b+"'][data-hidden!='y']").html(a).each(d);c("*[data-token='"+b+"'][data-hidden='y']").attr("data-trans",a).each(d)}}function E(b,a){clearTimeout(v);h.push(b);r.push(a);D(b,a);v=setTimeout(function(){var b=
{ln0:t_jp.lang,sr0:s,action:"tp_translation",items:h.length},a;for(a=0;a<h.length;a+=1)b["tk"+a]=h[a],b["tr"+a]=r[a],t+=c("*[data-token='"+h[a]+"']").size();c.ajax({type:"POST",url:t_jp.ajaxurl,data:b,success:function(){var b=t/k*100;t_jp.progress&&c("#"+m).progressbar("value",b)}});r=[];h=[]},200)}function l(b,a){E(b,c("<div>"+c.trim(a)+"</div>").text());var d=(k-c("."+e+'[data-source=""]').size())/k*100;t_jp.progress&&c("#"+n).progressbar("value",d)}function w(b,a,d){c.ajax({url:t_jp.ajaxurl,dataType:"json",
type:"GET",data:{action:"tp_gp",tl:d,q:b},success:a})}function x(b,a){w(a,function(a){c(a.results).each(function(a){l(b[a],this)})},t_jp.lang)}function y(b,a,d){c.ajax({url:"https://www.googleapis.com/language/translate/v2",dataType:"jsonp",data:{key:t_jp.google_key,q:b,target:d,source:t_jp.olang},traditional:!0,success:a})}function F(b,a){y(a,function(d){"undefined"!==typeof d.error?x(b,a):c(d.data.translations).each(function(a){l(b[a],this.translatedText)})},t_jp.lang)}function p(b,a,d){if(t_jp.msn_key){var f=
"[";c(b).each(function(a){f+='"'+encodeURIComponent(b[a].replace(/[\\"]/g,"\\$&").replace(/(\r\n|\n|\r)/gm," "))+'",'});f=f.slice(0,-1)+"]";c.ajax({url:"//api.microsofttranslator.com/V2/Ajax.svc/TranslateArray?appId="+t_jp.msn_key+"&to="+d+"&texts="+f,dataType:"jsonp",jsonp:"oncomplete",success:a})}else 1===z?setTimeout(function(){p(b,a,d)},500):(z=1,c.getScript("//www.microsofttranslator.com/ajax/v2/toolkit.ashx?loc=en&toolbar=none",function(){t_jp.msn_key=_mstConfig.appId;p(b,a,d)}))}function G(b,
a){s=2;p(a,function(a){c(a).each(function(a){l(b[a],this.TranslatedText)})},t_jp.binglang)}function A(b,a,d){c.ajax({url:"http://api.apertium.org/json/translate",data:{q:b,langpair:t_jp.olang+"|"+d,markUnknown:"no"},dataType:"jsonp",traditional:!0,success:a})}function H(b,a){s=3;A(a,function(a){200<=a.responseStatus&&300>a.responseStatus&&(void 0!==a.responseData.translatedText?l(b[0],a.responseData.translatedText):c(a.responseData).each(function(a){200===this.responseStatus&&l(b[a],this.responseData.translatedText)}))},
t_jp.lang)}function B(b,a){!t_jp.msn||"2"!==t_jp.preferred&&void 0!==t_jp.google?!t_jp.apertium||"en"!==t_jp.olang&&"es"!==t_jp.olang?t_jp.google_key?F(b,a):x(b,a):H(b,a):G(b,a)}function u(){var b=[],a=0,d=[],f=[];c("."+e+'[data-source=""]').each(function(){var e=c(this).attr("data-token"),g=c(this).attr("data-orig");void 0===g&&(g=c(this).html());1!==b[g]&&(b[g]=1,a+encodeURIComponent(g).length>I&&(B(f,d),a=0,d=[],f=[]),a+=encodeURIComponent(g).length,f.push(e),d.push(g))});B(f,d)}function C(b){"function"===
typeof c.xLazyLoader?b():(t_jp.$=c,c.getScript(t_jp.plugin_url+"/js/lazy.js",b))}function q(b){q.hit?b():(q.hit=!0,C(function(){c.fn.propAttr=c.fn.prop||c.fn.attr;c.xLazyLoader({js:t_jp.jQueryUI+"jquery-ui.min.js",css:t_jp.jQueryUI+"themes/"+t_jp.theme+"/jquery-ui.css",success:b})}))}var I=1024,k,e=t_jp.prefix,n=e+"pbar",m=n+"_s",s=1,t=0,v,h=[],r=[],z=0;t_jp.dgpt=w;t_jp.dgt=y;t_jp.dmt=p;t_jp.dat=A;t_jp.tfl=C;t_jp.tfju=q;t_jp.at=u;c(function(){t_jp.msn&&(t_jp.binglang=t_jp.lang,"zh"===t_jp.binglang?
t_jp.binglang="zh-chs":"zh-tw"===t_jp.binglang?t_jp.binglang="zh-cht":"mw"===t_jp.binglang&&(t_jp.binglang="mww"));c("."+e+"setdeflang").click(function(){c.ajax({url:t_jp.ajaxurl,data:{action:"tp_cookie"},cache:!1});c("."+e+"setdeflang").hide("slow");return!1});k=c("."+e+'[data-source=""]').size();c.ajaxSetup({cache:!0});k&&!t_jp.noauto&&(t_jp.google||t_jp.msn||t_jp.apertium)&&(t_jp.progress?q(function(){c("#"+e+"credit").css({overflow:"auto"}).append('<div style="float: left;width: 90%;height: 10px" id="'+
n+'"/><div style="margin-bottom:10px;float:left;width: 90%;height: 10px" id="'+m+'"/>');c("#"+n).progressbar({value:0});c("#"+m).progressbar({value:0});c("#"+m+" > div").css({background:"#28F828",border:"#08A908 1px solid"});u()}):u());t_jp.edit&&c.getScript(t_jp.plugin_url+"/js/transposhedit.js")})})(jQuery);

我应该在 checkout.js 中添加什么才能在每次更新购物车时触发翻译?

让我知道我还应该提供哪些其他详细信息。

编辑:我应该注意到,我被告知购物车正在通过 AJAX 进行更新。经过研究,transposh 的插件创建者建议用户查看 transposh.php 中的 on_init 函数

这是on_init函数:

    /**
     * Setup a buffer that will contain the contents of the html page.
     * Once processing is completed the buffer will go into the translation process.
     */
    function on_init() {
    tp_logger('init ' . $_SERVER['REQUEST_URI'], 4);

    // the wp_rewrite is not available earlier so we can only set the enable_permalinks here
    if (is_object($GLOBALS['wp_rewrite'])) {
    if ($GLOBALS['wp_rewrite']->using_permalinks() && $this->options->enable_permalinks) {
    tp_logger("enabling permalinks");
    $this->enable_permalinks_rewrite = TRUE;
    }
    }

    // this is an ajax special case, currently crafted and tested on buddy press, lets hope this won't make hell break loose.
    // it basically sets language based on referred when accessing wp-load.php (which is the way bp does ajax)
    tp_logger(substr($_SERVER['SCRIPT_FILENAME'], -11), 5);
    if (substr($_SERVER['SCRIPT_FILENAME'], -11) == 'wp-load.php') {
    $this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
    $this->attempt_json = true;
    }

    //buddypress old activity
    if (@$_POST['action'] == 'activity_get_older_updates') {
    $this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
    $this->attempt_json = true;
    }

    tp_logger($_SERVER['REQUEST_URI'], 5);
    if (strpos($_SERVER['REQUEST_URI'], '/wpv-ajax-pagination/') === true) {
    tp_logger('wpv pagination', 5);
    $this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
    }

    // load translation files for transposh
    load_plugin_textdomain(TRANSPOSH_TEXT_DOMAIN, false, dirname(plugin_basename(__FILE__)) . '/langs');

    //set the callback for translating the page when it's done
    ob_start(array(&$this, "process_page"));
    }

这是update_checkout()的函数

function update_checkout() {

        if (xhr) xhr.abort();

        if ( $('select#shipping_method').size() > 0 || $('input#shipping_method').size() > 0 )
            var method = $('#shipping_method').val();
        else
            var method = $('input[name=shipping_method]:checked').val();

        var payment_method  = $('#order_review input[name=payment_method]:checked').val();
        var country         = $('#billing_country').val();
        var state           = $('#billing_state').val();
        var postcode        = $('input#billing_postcode').val();
        var city            = $('input#billing_city').val();
        var address         = $('input#billing_address_1').val();
        var address_2       = $('input#billing_address_2').val();

        if ( $('#shiptobilling input').is(':checked') || $('#shiptobilling input').size() == 0 ) {
            var s_country   = country;
            var s_state     = state;
            var s_postcode  = postcode;
            var s_city      = city;
            var s_address   = address;
            var s_address_2 = address_2;
        } else {
            var s_country   = $('#shipping_country').val();
            var s_state     = $('#shipping_state').val();
            var s_postcode  = $('input#shipping_postcode').val();
            var s_city      = $('input#shipping_city').val();
            var s_address   = $('input#shipping_address_1').val();
            var s_address_2 = $('input#shipping_address_2').val();
        }

        $('#order_methods, #order_review').block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url + ') no-repeat center', backgroundSize: '16px 16px', opacity: 0.6}});

        var data = {
            action:             'woocommerce_update_order_review',
            security:           woocommerce_params.update_order_review_nonce,
            shipping_method:    method,
            payment_method:     payment_method,
            country:            country,
            state:              state,
            postcode:           postcode,
            city:               city,
            address:            address,
            address_2:          address_2,
            s_country:          s_country,
            s_state:            s_state,
            s_postcode:         s_postcode,
            s_city:             s_city,
            s_address:          s_address,
            s_address_2:        s_address_2,
            post_data:          $('form.checkout').serialize()
        };

        xhr = $.ajax({
            type:       'POST',
            url:        woocommerce_params.ajax_url,
            data:       data,
            success:    function( response ) {
                if ( response ) {
                    var order_output = $(response);
                    $('#order_review').html(order_output.html());
                    $('body').trigger('updated_checkout');
                }
            }
        });

    }

最佳答案

经过一番挖掘,因为我不是 php 专家,也不是 wp 专家,但我可以知道问题出在哪里。

首先你应该明白什么是add_action,它解释得很清楚here

如果您需要为“add_foobar”请求创建 AJAX 处理程序,您可以创建如下 Hook :

add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );

function prefix_ajax_add_foobar() {
    // Handle request then generate response using WP_Ajax_Response
}

使用上面的示例,只要将 AJAX 请求发送到 WordPress,并且该请求的“action”属性设置为“add_foobar”,该 Hook 就会自动执行。例如,以下代码将执行上面的钩子(Hook)。

jQuery.post(
    ajaxurl, 
    {
        'action': 'add_foobar',
        'data':   'foobarid'
    }, 
    function(response){
        alert('The server responded: ' + response);
    }
); 

现在你已经了解了 actions 是如何工作的,然后你必须从 transposh.php 文件中了解 transposh.php ajax 部分是如何工作的(我建议你在一个好的文本编辑器(如 sublime text)中打开该文件),一行一行437:

//buddypress old activity
        if (@$_POST['action'] == 'activity_get_older_updates') {
            $this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
            $this->attempt_json = true;
        }

这只是告诉我们的脚本在调用此操作时触发翻译,您所要做的就是稍微自定义此行,以便它在您的 ajax 请求(update_checkout()) 时触发。

如果您检查 update_checkout() 函数,您将找到相应的操作:'woocommerce_update_order_review'

解决方案:

<强>1。添加您的 wp 操作
add_action( 'wp_woocommerce_update_order_review', 'woocommerce_update_order_review' ); //最好将其与其他添加操作一起添加到 transposh.php 中的第 207 行。

<强>2。无需添加自己的功能,只需修改当前的 buddypress 示例即可。

if (@$_POST['action'] == 'activity_get_older_updates')

成为

if (@$_POST['action'] == 'activity_get_older_updates' || @$_POST['action'] == 'woocommerce_update_order_review' )
//fire translation if action is equal to buddypress activity get older updates or action is equal to woocommerce update checkout.

<强>3。这个人建议在 transposh.php 的第 352 行添加以下条件

if ($this->is_special_page($_SERVER['REQUEST_URI']))

成为

if ($this->is_special_page($_SERVER['REQUEST_URI'])&& !$this->attempt_json)

在这里找到:http://cl.ly/Shdn/o

我希望我有一个指向您正在使用此功能的页面的链接,但您无法提供示例,所以我希望该解决方案能够按预期工作。

关于javascript - 用于翻译 Ajax 加载内容的 Transposh 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940938/

相关文章:

css - 仅针对商店页面

javascript - Facebook 点赞评论删除 - 删除项目后更新数据列表

javascript - 如何 trim 文本?

php - 想要循环定位特定帖子

php - 从外部向 WordPress 插件的 PHP 文件添加函数(允许轻松更新版本)

java - C++ 到 Java 代码转换 : numberToBarcode()

ruby-on-rails - Ruby on Rails : what is the best choice of Web UI for managing I18n yml files?

Python:如何用半角字符替换全角字符?

javascript - 使用 For 循环在 AJAX 函数中创建数组并提供值

javascript - CSS - 使用悬停以不同方式影响多个元素