简体   繁体   中英

Passing a JSON encoded PHP array to HTML onclick

I'm trying to populate my jquery datatables and I've been successful in doing so. Except when I'm passing a JSON encoded string in one of the javascript function parameters in the html tag. I'm using the following code from PHP. As seen below, I'm passing a json_encode of the $update_data variable on the last parameter of the function in the onclick part.

                       $update_data = 
                            array(
                            array('Page type',array( array('1 - Standard','Standard'), array('2 - HTML','HTML') ),'select','noval'),
                            array('title',$row->title,'input','val'),
                            array('header',$row->header,'input','noval'),
                            array('footer',$row->footer,'input','noval'),
                            );

$subarray[]='<center> <span data-target="#updatepost'.$row->_id.'" data-toggle="modal" onclick="easy_update(\'update\',\'post\',\'book/update-book-folder-designation\','.$row->_id.',\'Update Pages\',\''.json_encode($update_data).'\')" class="btn fa fa-pencil"></span> </center>';

Then I get an error of

Uncaught SyntaxError: Invalid or unexpected token

When I'm calling the function from the onclick. But the javascript error line points to nothing.

My javascript function is simply as

function easy_update(type,method,url,id,header_title,data){

 }

I suspect it's about the formatting of the json string that causes the mess in reading the parameters of my js function but I'm not sure. Here is the image of my rendered html tag from the inspect element

渲染视图

I dont get any errors when i replace the json encoded string with a regular string as parameter. I Hope i give enough information about the problem.

I suppose you are trying to use string parameter as JS object on client function easy_update() . Try to send the data without quotes like this:

$subarray[]='<center> <span data-target="#updatepost'.$row->_id.'" data-toggle="modal" onclick="easy_update(\'update\',\'post\',\'book/update-book-folder-designation\','.$row->_id.',\'Update Pages\','.json_encode($update_data).')" class="btn fa fa-pencil"></span> </center>';

Also you need to replace quotes in tags or in json_encode() results as example:

$var = str_replace('"', '\'', json_encode($update_data));

And then send it to function, One of the possible options will be:

$encoded = str_replace('"', '\'', json_encode($update_data));
$subarray[]='<center> <span data-target="#updatepost'.$row->_id.'" data-toggle="modal" onclick="easy_update(\'update\',\'post\',\'book/update-book-folder-designation\','.$row->_id.',\'Update Pages\','.$encoded.')" class="btn fa fa-pencil"></span> </center>';

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