我在textarea中有一个JSON代码,我希望得到它并使用它,因为它存在于我的网站中。
这是textarea代码:
<textarea>
var settings = [
{
"id" : "post_thumbnail",
"name" : "Default Post Thumbnail",
"desc" : "The image src that you want to use for non-thumbnail posts.",
"type" : "text",
"std" : "http://lorempixel.com/640/300/"
}
]
</textarea>
我尝试了这个但不幸的是,只有当代码存在于网站而不是textarea中时它才有用,因为我收到了这个错误:
未捕获的ReferenceError:未定义设置
for( var i = 0; i < settings.length; i++){
var setting_id = settings[i].id,
setting_name = settings[i].name,
setting_desc = settings[i].desc,
setting_type = settings[i].type,
setting_std = settings[i].std;
$('body').html(setting_id +'<br>'+ setting_name +'<br>'+ setting_desc +'<br>'+ setting_type +'<br>'+ setting_std);
}
这是一个现场演示:http://jsfiddle.net/tauv0or1/
答案 0 :(得分:8)
textarea
的值不会被解析为JavaScript。而是将值更改为有效的JSON:
<textarea>
[
{
"id" : "post_thumbnail",
"name" : "Default Post Thumbnail",
"desc" : "The image src that you want to use for non-thumbnail posts.",
"type" : "text",
"std" : "http://lorempixel.com/640/300/"
}
]
</textarea>
调整您的JavaScript以使用JSON.parse
值:
var field = document.getElementById("the_textarea");
var settings = JSON.parse(field.value);
因为用户可以在textarea中输入任意信息,所以您可能希望将JSON.parse
包装在try-catch块中,并提醒用户语法错误:
var settings = null;
try {
settings = JSON.parse(field.value);
}
catch (error) {
if (error instanceof SyntaxError) {
alert("There was a syntax error. Please correct it and try again: " + error.message);
}
else {
throw error;
}
}
答案 1 :(得分:2)
您需要首先评估文本,然后将其实际运行为javascript:
eval($('textarea').text());
http://jsfiddle.net/tauv0or1/1/
或者,您可以将其解析为JSON,但您需要先编辑textarea的内容:
var settings = JSON.parse($('textarea').text());