简体   繁体   English

javascript语法错误,缺少“;”

[英]javascript syntax error, missing “;”

I have a form with potential errors in the form defined in php. 我在php中定义的表单中存在潜在错误的表单。 I'm used javascript to change the form action depending on whether errors are present or not. 我使用JavaScript来更改表单操作,具体取决于是否存在错误。 I've converted the php error variable, $errors using json_encode so I can use it in javascript. 我已经使用json_encode转换了php错误变量$ errors,因此可以在javascript中使用它。 Running the file in Firefox I get the following error in Firebug: 在Firefox中运行文件,我在Firebug中收到以下错误:

Syntax error: missing ; 语法错误:缺少;

before statement var errors = "{"firstnameErr:......etc} , with the pointer at the letter f in firstnameErr. before语句var errors = "{"firstnameErr:......etc} ,指针位于firstnameErr中的字母f处。 It looks like I have the errors in the json_encode object. 看来我在json_encode对象中有错误。

Here is the javascript: 这是JavaScript:

 <script type = "text/javascript">
    function switchFormAction() { 
    var errors = [];                               
    var errors = "<?php echo json_encode($errors); ?>";
    if(!empty(errors)) {
    alert("Please correct these errors");
    }                                        
    else    {
    var element = document.getElementById("regForm");
    element.setAttribute("action", "serraInsertForm.php");
    return true;
    }
    }
    window.onload = function() {
    document.getElementById("regForm").onsubmit = function()
    switchFormAction();
    }
</script>  

Probably something simple but I can't work it out. 可能很简单,但我无法解决。 Javascript and json are new to me. Javascript和json对我来说是新的。 Appreciate any help stackoverflow can offer. 感谢stackoverflow可以提供的任何帮助。

var errors = "<?php echo json_encode($errors); ?>";
             ^---                                ^--

The indicated quotes are not necessary and are in fact causing the problem. 指示的引号不是必需的,实际上是引起问题的原因。 json_encode() will produce whatever quotes/brackets are necessary to turn the data in $errors into syntactically valid Javascript. json_encode()将产生将$errors的数据转换为语法有效的Javascript所需的任何引号/括号。 You're producing: 您正在制作:

var errors = "{"somekey":"somevalue"}";
             ^--start string
               ^--end string
                ^^^^^^^ undefined variable

All you need is 所有你需要的是

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

Losing the quotes around here ought to do it. 应该在这里丢掉引号。

var errors = "<?php echo json_encode($errors); ?>";

Should probably be: 应该可能是:

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

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

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