简体   繁体   中英

How to properly concatenate values coming from Javascript and PHP?

I have been struggling with this for the last two hours and I can't get it to work. Take a look to the following piece of code:

$js = '$.extend($.fn.fmatter , {
            userActions : function(cellvalue, options, rowData, addOrEdit) {
            var data = cellvalue.split("|");
            var id = options.rowId;
            var actions = "";';

foreach ($editorActions as $linkType => $value) {
    switch ($linkType) {
        case 'view':
            $js .= "if(data[1] == 1) {
                        actions += \"<a class='actionimage' href='" . $value . " + options.rowId' title='" . $this->translate->_e('View') . "' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>\";
                    }";
    }

    break;
}

As you can see id is a value coming from Javascript and $value is coming from PHP. The idea is to get an hyperlink as for example:

$value = "/route/to/function/";
id = 19009; // I've omitted the $ sign since this var is coming from JS

var href = "' . $value . '" + id;'

Then I need to use the href var as part of the <a> element shown right after the definition.

With my code above I am getting this error:

Uncaught SyntaxError: Invalid or unexpected token

Can I get some help to get this right?

UPDATE:

This is how the code looks like after I render the page:

$(function () {
    $.extend($.fn.fmatter, {
        userActions: function (cellvalue, options, rowdata) {
            var data = cellvalue.split('|');
            var id = options.rowId;
            var actions = '';

            console.log(id);
            if (data[1] == 1) {
                actions += "<a class='actionimage' href='/sf/distributor/show/ + options.rowId' title='View' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>";
            }

            return actions;
        }
    });
});

Notice how the function $.extend close properly. console.log(id) did print the value of options.rowId however this value doesn't have any effect on the hyperlink as you may notice this is the value /sf/distributor/show/ + options.rowId .

What is coming in $value is a plain string in the case above /sf/distributor/show/ .

You're missing double quotes and to end and reopen the string around options.rowId and a + in:

actions += \"<a class='actionimage' href='" . $value . " + options.rowId'

It should be:

actions += \"<a class='actionimage' href='" . $value . "\" + options.rowId + \"'

在这里,您缺少“”,因此您将options.rowId添加为字符串文本。

href='/sf/distributor/show/" + options.rowId + "' 

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