简体   繁体   中英

Yii framework, pass jquery parameters into Yii::app()->createUrl('controller/action',array('param'=>'value')

I'm new in yii and I have this script in one of my views:

$('#div_exams').on('click', 'a[id^="download"]', function(e) {

    e.preventDefault();

    var fileName = e.target.id;

    $.ajax({
        type: "POST",
        url: "<?php echo Yii::app()->createUrl("exams/downloadExam",array('fileName'=>'HERE I NEED TO PASS FILENAME')); ?>",

        success: function(jsonResponse) {


        },
        error: function() {

        }
    });

});

So my question is, how can I pass the var fileName in javascript to create the url in yii?

Thank you very much :)

Option 1: Build a URL template in Yii and interpolate each needed filename into it:

var baseUrl = <?php echo json_encode(Yii::app()->createUrl("exams/downloadExam",array('fileName'=>'__PLACEHOLDER__'))); ?>; 

$('#div_exams').on('click', 'a[id^="download"]', function(e) {
  ...
  var url = baseUrl.replace('__PLACEHOLDER__', encodeURIComponent(filename));
  ...
}

Option 2, probably cleaner: Build each URL in Yii, attach it to the link as a data- attribute , read it using JS:

// when building each download link:

<?php echo CHtml::link('Download link, 'some url', array(
  'id' => 'download_1234',
  'data-download' => Yii::app()->createUrl("exams/downloadExam",array('fileName'=>'the file')),
));

// in the script

$('#div_exams').on('click', 'a[id^="download"]', function(e) {
  ...
  var url = $(this).data('download');
  ...
}

Note that neither solution abuses the id attribute like you're doing now.

If I understand your problem correctly, you need to create an URL for downloading something with Javascript?

That is not possible. JS does not work server side so you can not create an URL using PHP code inside the JS function once its loaded in the client (browser).

You can however, have an action in Yii that you pass a value and it echoes a URL, you get that URL with Jquery (responseText I think) and use it whenever you want.

You could also pass the filename as POST data if you use the data option in jQuery.ajax() :

$('#div_exams').on('click', 'a[id^="download"]', function(e) {

    e.preventDefault();

    var fileName = e.target.id;

    $.ajax({
        type: "POST",
        url: "<?php echo Yii::app()->createUrl("exams/downloadExam"); ?>",
        data: {fileName: fileName},
        success: function(jsonResponse) {


        },
        error: function() {

        }
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM