TCM*_*TCM 1 javascript php codeigniter
你好,这是我的 onload 函数:-
$(function() {
<?php if( isset ($this->validation->error_string) && $this->validation->error_string != '') {?>
str = '<?php echo $this->validation->error_string;?>';
alert(str);
<?php }?>
});
Run Code Online (Sandbox Code Playgroud)
我总是收到这个错误:-
unterminated string literal
str = '<p>The Username field is required.</p>\n
Run Code Online (Sandbox Code Playgroud)
即使存在验证错误,我总是在 firebug 中收到此错误。然而,当我只是在正文标签中回显它时,它工作得很好。我该如何解决这个问题?
提前致谢 :)
您需要在输出中对新行进行编码,使其成为有效的 JavaScript,例如使用json_encode(),如下所示:
$(function() {
<?php if( isset ($this->validation->error_string) && $this->validation->error_string != '') {?>
var str = '<?php echo json_encode($this->validation->error_string);?>';
alert(str);
<?php }?>
});
Run Code Online (Sandbox Code Playgroud)
JavaScript 字符串不能跨行...您将收到“未终止的字符串文字”错误,正是您所看到的。另外,使用varas 不创建全局变量,或者根本不使用变量,如下所示:
$(function() {
<?php if( isset ($this->validation->error_string) && $this->validation->error_string != '') {?>
alert('<?php echo json_encode($this->validation->error_string);?>');
<?php }?>
});
Run Code Online (Sandbox Code Playgroud)
另请注意,由于您正在警告这一点,因此您可能需要删除<p></p>包装器,因为它也会显示在中alert()。
| 归档时间: |
|
| 查看次数: |
603 次 |
| 最近记录: |