简体   繁体   English

firefox抱怨有效的json…看不见的无效字符?

[英]firefox complaining about valid json… invisible invalid character?

I'm writing a php script that needs to load a 2D array into a js variable as json. 我正在编写一个PHP脚本,该脚本需要将2D数组作为json加载到js变量中。 First i make the array then use json_encode to turn it into a string. 首先,我制作数组,然后使用json_encode将其转换为字符串。 Then I run a small bit of js to get it accessable on the client side. 然后,我运行一小段js以使其可在客户端访问。 Like so: 像这样:

$sBaseData = Filters::$sFilterBaseTypeData;
$sBaseData = str_replace('\r',' ',$sBaseData);
$sBaseData = str_replace('\n',' ',$sBaseData);
$sBaseData = str_replace('\t',' ',$sBaseData);

echo <<<HTML
    <script type="text/javascript">
        var validation_data = JSON.parse('$sBaseData');
    </script>
HTML;

Firefox complains about an unexpected character here: Firefox在这里抱怨一个意外的字符:

var validation_data = JSON.parse('{"enumeration":{"js":"","msg":""},"date":{"js":" var parts = widget.value.split('-'); var d = new Date(parts[0],parts[1],parts[2]); PASS = (d.getDay()>=1); ","msg":"Invalid date. Please Enter a date in the format: YYYY-MM-DD"},"text":{"js":"","msg":"what did you do?"},"integer":{"js":"if (isNaN(widget.value)) { PASS = false; } else { intVal = parseInt(widget.value); PASS = (widget.value == intVal); } ","msg":"Please enter an integer value"},"decimal":{"js":"PASS = isNaN(widget.value); ","msg":"Please enter a number"},"group":{"js":"","msg":""},"dealer":{"js":"","msg":""}}')

I tried using http://jsonlint.com/ to find out which character was at fault but it says it's all valid and wonderful. 我尝试使用http://jsonlint.com/来找出哪个字符有问题,但是它说的确很有效。 I replaced some characters that were causing issues, is there anything else I should be replacing? 我替换了引起问题的某些字符,还有什么我需要替换的?

Uh... 嗯...

 var parts = widget.value.split('-'); 

Putting that in a string that uses single quotes will break it. 将其放在使用单引号的字符串中会破坏它。 Use a JSON encoder to output your JavaScript literal . 使用JSON编码器输出JavaScript文字

The problem is you have ' in your string while you are using ' to quote the string. 问题是你有'在您的字符串,而你正在使用'引用的字符串。

If your json string is valid, you don't need to parse it even. 如果您的json字符串有效,则甚至不需要解析它。 The below will work. 以下将工作。

echo <<<HTML
    <script type="text/javascript">
        var validation_data = {$sBaseData};
    </script>
HTML;

Your JSON is valid but in your js code the simple quote closes the parse function's argument. 您的JSON有效,但在js代码中,简单的引号关闭了解析函数的参数。

Try like this: 尝试这样:

"date":{"js":" var parts = widget.value.split(\'-\');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM