2014-11-15 250 views
2

我試圖讓transposh plugin翻譯每次購物車動態更新。目前,該插件將翻譯,然後woocommerce將更新購物車,因此翻譯消失。Transposh插件來翻譯Ajax加載內容

我發現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的插件製作者曾建議用戶看on_init functiontransposh.php

這是on_init function

/** 
    * 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'); 
       } 
      } 
     }); 

    } 
+0

結帳與更新購物車不同,您要啓動哪種翻譯?如果你提供一個例子,它也會更好。 – ProllyGeek 2014-11-22 14:39:06

+0

我不知道如何提供一個例子,因爲我不知道答案是什麼。我也不確定您的結帳時間是否與更新購物車不同,但我可以告訴您,當您處於結算髮貨頁面時,購物車摘要(總費用位於此處)通過AJAX進行更新,用戶正在更改其送貨地點。在更改運送地點後,由於購物車摘要已更新,翻譯將被清除。所以理想情況下,我希望翻譯在更新時再次觸發。 – chdltest 2014-11-22 19:08:20

回答

1

功能的後位的挖掘,因爲即時通訊不是PHP專家既不是專家,但我可以告訴問題在哪裏。

首先,你應該明白什麼add_action,它是很好的解釋here

如果你需要一個「add_foobar」請求創建一個AJAX的處理程序,您可以創建這樣一個鉤子:

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'時,該鉤子將自動執行。例如,下面的代碼將執行上面的鉤子。

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

那麼現在你有怎樣的行爲作品,那麼你必須得到如何transposh.php ajax的部分作品,從transposh.php文件(我建議你像崇高文本良好的文本編輯器打開文件),符合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

我希望我有一個鏈接到您的網頁,你使用這個,但你不能提供一個例子,所以我希望這個解決方案將工作,因爲它的意思是。

+1

你在沒有你請求的例子的情況下工作,你也向我解釋了很多。即使我找到了替代品,因爲我是一隻迷失的小羊羔,但我決定恢復我的變化並採用你的方法,因爲......因爲它有效!再次感謝您的教學和花時間來幫助我。 – chdltest 2014-11-23 18:37:41

+0

@chdltest很高興我能幫你:) – ProllyGeek 2014-11-23 18:38:58