简体   繁体   English

eval() 函数不起作用

[英]eval() function not working

im trying to convert a json string from my .php file using eval() function but it doesnt work.我正在尝试使用 eval() 函数从我的 .php 文件中转换一个 json 字符串,但它不起作用。 the browser console says SyntaxError: expected expression, got '<'...浏览器控制台显示 SyntaxError: expected expression, got '<'...

but when i comment out the line where eval() is, and use document.write(data);但是当我注释掉 eval() 所在的行并使用 document.write(data); the string appears...字符串出现...

here's my code..这是我的代码..

<html>
<head>
    <script type='text/javascript' src='jquery.js'></script>
    <script type='text/javascript'>

    var go = function() {

        $.get("testjson.php", function(data) {

            var obj = eval("(" + data + ")");

            document.write(obj.name + "<br />");
            document.write(obj.date + "<br />");
        });
    }
    </script>
</head>
<body>
    <input type='button' value='go' onclick='go()' />
<body>
</html>

and here's the code of my testjson.php file...这是我的 testjson.php 文件的代码...

<?php

    $msg = array(
        "name"=>"hi there Victor!",
        "date"=>"Monday 21st Feb 2010"
    );

    $myMsg = json_encode($msg);

    echo $myMsg;

?>

im using latest version of jquery..我正在使用最新版本的 jquery ..

There are other suggestions in the comments and answers here about using $.getJSON() instead of eval() , or specifying json as a parameter in $.get() , and these are all good suggestions.关于使用$.getJSON()而不是eval()或在$.get()指定json作为参数的评论和答案中还有其他建议,这些都是很好的建议。 But, they aren't the reason this isn't working.但是,它们不是这不起作用的原因。

Simply, you're missing a semi-colon in your var go = .... function definition after the closing brace near the bottom.简单地说,您在var go = ....底部附近的右大括号之后的函数定义中缺少一个分号。

the code is now fixed!代码现已修复! lol i don't know why, but i just removed the commented html code under my .php code... how the heck it affects my code in the first place??大声笑我不知道为什么,但我只是删除了我的 .php 代码下的注释 html 代码......它首先如何影响我的代码? it's just a comment... :/这只是一个评论...:/

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

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