[英]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. 我正在开发一个发票系统和我的mvc框架中的控制器,现在,使用单引号括起来的字符串。 I am new to javascript but I couldn't avoid it. 我是javascript的新手,但我无法避免它。 I have function that works and validates in a window.onload declaration but the same declaration inside the form creates an error. 我有一个在window.onload声明中工作和验证的函数,但表单内的相同声明会产生错误。 The html output is: html输出是:
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. 所有值都为null,因为没有创建任何值。 in Firebug I get the error " SyntaxError: unterminated string literal". 在Firebug中我收到错误“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
值只是:
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
: 作为值的一部分的双引号需要进行转义/编码,这可以通过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 : 虽然,另一种选择是利用JSON与JavaScript的关系,输出JSON字符串,以便将其视为JavaScript Object
文字 :
'... onclick=\'verifyAccount('.$accounts.');\' ...'
Or, if $results
still needs to be encoded as JSON: 或者,如果$results
仍然需要编码为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
. 这种依赖性是需要调整verifyAccount
以期望Object
而不是String
。
Here is my suggestion 这是我的建议
javaScript: JavaScript的:
var account = <?php echo json_encode($accounts)?>;
or if you for some reason cannot get rid of the single qutotes: 或者,如果你由于某种原因无法摆脱单个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: 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: 你可以在这里纠正我,但我相信这是你试图插入的PHP变量,所以它真的应该成为:
<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: 为了防止单引号( '
)和双引号( "
)打破你的onclick
封装,你需要摆脱其中的一个。因为我偏爱属性中的双引号,并考虑到json_encode
返回双引号,这就是我的所作所为:
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: 哪个将由PHP导出到:
{"user1":"Username is 'quit3\" strange and \\ problematic!"}
So it ends on: 所以结束于:
<label><input type="radio" name="account" id="account" onclick="var user ={"user1":"Username is 'quit3\\" strange and \\\\ problematic!"}; console.log(user.user1);"/> Click me!</label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.