【发布时间】:2010-10-31 21:53:49
【问题描述】:
这是我通过 getjson 从服务器收到的 JSON 数据格式:[{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}]。我需要在用户输入中附加 json。我正在尝试以这种方式进行操作:首先将其转换为 javascript 对象,将其附加到用户输入中,再次转换为 json 对象并将其发送回服务器以进行数据库更新。我已经使用 eval() 将 json 转换为 javaScript 对象。现在无法操作 javascript 对象。如果我将 javascript 对象转换回 json 对象,它会正确显示从服务器发送的所有数据。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input></p>
<p><input type = "button" id = "send" name = "send" value = "send"
onClick="ADDLISTITEM();"></input></p>
<select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{// this script suffers from errors on eval/JSON.parse methods
alert (json.length);//outputs corrcet with eval
tring = JSON.stringify(json);//outputs corrcet with eval
alert(jsonString);//outputs corrcet with eval
alert(json.options[0]);//no output
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script src="http://www.json.org/json2.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = eval(jsonData);
//json = JSON.parse(jsonData);/*error if uncomment:"IMPORTANT: Remove this line from
json2.js before deployment"*/
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});});
});
</script>
</body>
</html>
【问题讨论】:
-
你的 HTML 代码有点破...
-
不要使用 eval() 来解析你的 JSON。使用 JSON.parse(),并包含此文件以兼容旧版浏览器:json.org/json2.js
-
除了 Golmote 的建议之外:1. 使用 doctype,2. 您不需要 SCRIPT 元素上的语言和类型属性,3. 考虑使用仅使用大写函数名称的约定对于构造函数 4. 考虑在声明使用这些变量的全局函数之前声明全局变量 5. 使用小写标签名称 6. 考虑将 SCRIPT 元素放在页面底部(就在
标签: javascript json eval