简体   繁体   中英

How to pass a JSON array to a javascript function inside a string in php

I am working on an invoicing system and the controller in my mvc framework, for now, uses strings enclosed in single quotes. I am new to javascript but I couldn't avoid it. I have function that works and validates in a window.onload declaration but the same declaration inside the form creates an error. The html output is:

onclick="verifyAccount('{"1":null,"2":null,"3":null,"4":null,"5":null,"8":null,"9":null,"10":null,"21":null,"22":null}');" >

all the values are null because none have been created. in Firebug I get the error " SyntaxError: unterminated string literal". I don't know what is needed to solve this. The line that causes the error is:

    <input type="radio" name="account" id="account" onclick="verifyAccount(\''.$accounts.'\');" >

    $form = '
    <script type="text/javascript">

    window.onload = function() {
    document.getElementById("addLabor").onclick = function(){ addLabor("labor"); }
    document.getElementById("addPart").onclick = function(){ addPart("parts"); }
    document.getElementById("addAdjustment").onclick = function(){ addAdjustment("adjustments"); }
    document.getElementById("customer_id").onchange = function() { verifyAccount(\''.$accounts.'\'); }
    addLabor("labor");

    }

    </script>
$form = '
<script type="text/javascript">

window.onload = function() {
    document.getElementById("addLabor").onclick = function(){ addLabor("labor"); }
    document.getElementById("addPart").onclick = function(){ addPart("parts"); }
    document.getElementById("addAdjustment").onclick = function(){ addAdjustment("adjustments"); }
    document.getElementById("customer_id").onchange = function() { verifyAccount(\''.$accounts.'\'); }
    addLabor("labor");

    }

    </script>

    <form method="POST" class="formTable" id="addInvoice" action="/invoices/save"
onsubmit="return(validate());">
        <table class="buttons" >
            <tr>
            <td><input type="button" id="addLabor" value="Add labor"/></td>
            <td><input type="button" id="addPart" value="Add part"/></td>
            <td><input type="button" id="addAdjustment" value="Adjust"/></td>
            <td><input type="submit" name="Save" value="Save" /></td>
        </tr>
    </table>
    <table id="invoiceTable">
        <tr>
            <td><label>Date:</label></td>
            <td><input type="text" id="date" name="date" maxlength="10" size="4" />
                <a href="javascript:NewCal(\'date\',\'MMDDYYYY\')">
                <img src="/images/cal.gif" width="16" height="16" alt="Pick a date"></a>
            </td>
        </tr>
        <tr>
            <td><label>Use Account?:</label></td>
            <td><input type="radio" name="account" id="account" onclick="verifyAccount(\''.$accounts.'\')" ></td>
        </tr>
        <tr>
            <td><label>Work Order Number:</label></td>
            <td><input type="text" name="number" id="number" maxlength="8" size="6" /></td>
        </tr>
        <tr>
            <td><label>Customer:</label></td>
            <td><select name="customer_id" id="customer_id" >'.$select.'</select></td>
        </tr>
        <tr>
            <td><label>Job Name:</label></td>
            <td><input type="text" name="job_name" id="job_name" /></td>
        </tr>
    </table>
    <table id="labor"></table>
    <table id="parts"></table>
    <table id="adjustments"></table>
    <table id="payment"></table>

    </form>';
        $this->component($form);
     <form method="POST" class="formTable" id="addInvoice" action="/invoices/save"
onsubmit="return(validate());">
    <table class="buttons" >
        <tr>
            <td><input type="button" id="addLabor" value="Add labor"/></td>
            <td><input type="button" id="addPart" value="Add part"/></td>
            <td><input type="button" id="addAdjustment" value="Adjust"/></td>
            <td><input type="submit" name="Save" value="Save" /></td>
        </tr>
    </table>
    <table id="invoiceTable">
        <tr>
            <td><label>Date:</label></td>
            <td><input type="text" id="date" name="date" maxlength="10" size="4" />
                <a href="javascript:NewCal(\'date\',\'MMDDYYYY\')">
                <img src="/images/cal.gif" width="16" height="16" alt="Pick a date"></a>
            </td>
        </tr>
        <tr>
            <td><label>Use Account?:</label></td>
            <td><input type="radio" name="account" id="account" onclick="verifyAccount(\''.$accounts.'\')" ></td>
        </tr>
        <tr>
            <td><label>Work Order Number:</label></td>
            <td><input type="text" name="number" id="number" maxlength="8" size="6" /></td>
        </tr>
        <tr>
            <td><label>Customer:</label></td>
            <td><select name="customer_id" id="customer_id" >'.$select.'</select></td>
        </tr>
        <tr>
            <td><label>Job Name:</label></td>
            <td><input type="text" name="job_name" id="job_name" /></td>
        </tr>
    </table>
    <table id="labor"></table>
    <table id="parts"></table>
    <table id="adjustments"></table>
    <table id="payment"></table>


</form>';
        $this->component($form);

The problem are all the double-quotes, which keep starting and ending strings. This results in the onclick value being just:

onclick="verifyAccount('{"

With the rest being at best additional attributes or just junk.

The double-quotes that are part of the value need to be escaped/encoded, which can be done with htmlentities :

'... onclick="verifyAccount(\''.htmlentities($accounts).'\');" ...'

Though, another option is to take advantage of JSON's relation to JavaScript, outputting the string of JSON so that it's treated as a JavaScript Object literal :

'... onclick=\'verifyAccount('.$accounts.');\' ...'

Or, if $results still needs to be encoded as JSON:

'... onclick=\'verifyAccount('.json_encode($accounts).');\' ...'

Resulting in:

<... onclick='verifyAccount({"1":null,"2":null",...})'>

The dependency of this is that verifyAccount would need to be adjusted to expect an Object rather than a String .

Here is my suggestion

javaScript:

var account = <?php echo json_encode($accounts)?>;

or if you for some reason cannot get rid of the single qutotes:

 var account = JSON.parse('{"1":null,"2":null,"3":null,"4":null,"5":null,"8":null,"9":null,"10":null,"21":null,"22":null}');

HTML:

<input type="radio" name="account" id="account" onclick="verifyAccount(account)" />

or with less change:

echo '<input  ... onclick=\'verifyAccount('.json_encode($accounts).');\' >';

I believe you're just missing the concatenation operators here.

So:

<input type="radio" name="account" id="account" onclick="verifyAccount(\''.$accounts.'\');" >

Becomes:

<input type="radio" name="account" id="account" onclick="verifyAccount('\'' + '.$accounts.' + '\'');" >

And you can correct me here, but I believe that is a PHP variable you're trying to insert there, so it really should become:

<input type="radio" name="account" id="account" onclick="verifyAccount('\'' + '.<?php echo $accounts ?>.' + '\'');" >

To prevent both single quotes ( ' ) and double quotes ( " ) to break your onclick encapsulation, you need to get rid of one of the two. As I have a preference for double quotes in attributes, and considering that json_encode returns double quotes, here's what I do:

echo '<input type="radio" name="account" id="account" onclick="verifyAccount('.htmlspecialchars(json_encode($accounts)).');"/>';

For example, the following object will work as expected:

array('user1' => 'Username is \'quit3" strange and \\ problematic!');

Which will be exported by PHP to:

{&quot;user1&quot;:&quot;Username is 'quit3\&quot; strange and \\ problematic!&quot;}

So it ends on:

 <label><input type="radio" name="account" id="account" onclick="var user ={&quot;user1&quot;:&quot;Username is 'quit3\\&quot; strange and \\\\ problematic!&quot;}; console.log(user.user1);"/> Click me!</label> 

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