如何将 JSON 数组传递给 php 字符串中的 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17636530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a JSON array to a javascript function inside a string in php
提问by Corey Ray
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:
我正在开发一个发票系统,我的 mvc 框架中的控制器现在使用单引号括起来的字符串。我是 javascript 的新手,但我无法避免它。我有一个在 window.onload 声明中工作和验证的函数,但表单内的相同声明会产生错误。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. 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:
所有的值都是空的,因为没有创建。在 Firebug 中,我收到错误“SyntaxError:未终止的字符串文字”。我不知道需要什么来解决这个问题。导致错误的行是:
<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);
回答by Jonathan Lonowski
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 字符串,以便将其视为JavaScriptObject
文字:
'... 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
需要调整以期望 anObject
而不是 a String
。
回答by mplungjan
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:
HTML:
<input type="radio" name="account" id="account" onclick="verifyAccount(account)" />
or with less change:
或更改较少:
echo '<input ... onclick=\'verifyAccount('.json_encode($accounts).');\' >';
回答by Yvan
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>
回答by Myles
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 ?>.' + '\'');" >