2013-04-18 33 views
1

我想在ajax後建立一個令牌,但沒有得到控制器方法的認可。該的javascrip看起來它遵循joomla令牌沒有得到控制器方法識別

jQuery(document).ready(function() { 
    jQuery('#source').change(function() { 
     jQuery('#fileupload').addClass('fileupload-processing'); 
     var data = jQuery('#source option:selected').val(); 
     jQuery.post('index.php', { 
      'option': 'com_tieraerzte', 
      'task': 'parser.importColumns', 
      'tmpl': 'component', 
      'token':'<?php echo JUtility::getToken()?>', 
      'app': data, 
      'dataType': 'html', 
     }, function(result) { 
      jQuery('td.add_column').html(result); 
      jQuery('button#parse.btn').show(); 
      //edit the result here 
      return; 
     }); 
    }); 

是如何產生的令牌,並在控制器我檢查托克是否存在等貼

但拋出我的無效令牌

控制器檢查托克

JRequest::checkToken('request') or jexit('Invalid Token'); 

回答

9

你幾乎在那裏,它只是有點混。 Joomla!形式表徵生成並以1所以值作爲一份輸入名稱,標記看起來像這樣在您的形式:

<input type="hidden" name="1LKJFO39UKSDJF1LO8UFANL34R" value="1" />

考慮到這一點,通過AJAX提交的時候,你需要設置參數名稱到您的標記名稱,與值1。我完成類似的東西只要使用該jQuery('selector').serialize()方法:

Joomla.autoSave = function() { 
    jQuery.ajax({ 
    url: "index.php?option=com_gazebos&task=product.apply&tmpl=component", 
    type: "POST", 
    data: jQuery("#product-form").serialize(), 
    success: function (data) { 
     console.log("autosaved"); 
    } 
    }); 
}; 

這樣做提取所有形式的數據(包括隱藏的輸入形式令牌)並將其格式化爲查詢字符串,然後將其與請求一起發送。但是,在我看來,你可能不想這樣做,而且你只是想提交一點數據,而不是整個表單。所以,讓我們返工你的代碼一點點地得到想要的效果:

/** 
* First, let's alias $ to jQuery inside this block, 
* then setup a var to hold our select list dom object. 
*/ 
jQuery(document).ready(function ($) { 
    var sourceSelect = $('#source'); 

    sourceSelect.change(function() { 
     $('#fileupload').addClass('fileupload-processing'); 

     /** 
     * Use the token as a parameter name and 1 as the value, 
     * and move the dataType param to after the success method. 
     */ 
     $.post('index.php', 
      { 
      'option': 'com_tieraerzte', 
      'task':  'parser.importColumns', 
      'tmpl':  'component', 
      'app':  sourceSelect.val(), 
      '<?php echo JSession::getFormToken()?>': 1 
      }, 
      function(result) { 
      $('td.add_column').html(result); 
      $('button#parse.btn').show(); 
      //edit the result here 
      return; 
      }, 
      'html' 
     ); 
    }); 
}); 

最後,該代碼是假設你有這樣的JS代碼無論是在你的view.html.php或在您的views/parser/tmpl/default.php。如果你有一個單獨的.js文件,那麼你的php代碼將不會執行,並給你的令牌。

+0

唐偉大一如既往!謝謝。 –