Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery解析来自div的JSON_Javascript_Jquery_Json_Html - Fatal编程技术网

Javascript jQuery解析来自div的JSON

Javascript jQuery解析来自div的JSON,javascript,jquery,json,html,Javascript,Jquery,Json,Html,我是jQuery的初学者,我试图使用$.getJSON函数从div解析JSON数据,但它不起作用。你能告诉我怎么做吗?以下是我正在使用的代码: <div id="json"> {"data":[ {"a":"b"}, {"a":"c"} ]} </div> <script> $(document).ready(function() { $.getJSON( $("#json").html() , function(j

我是jQuery的初学者,我试图使用
$.getJSON
函数从div解析JSON数据,但它不起作用。你能告诉我怎么做吗?以下是我正在使用的代码:

<div id="json">
   {"data":[
     {"a":"b"},
     {"a":"c"}
   ]}
</div>

<script>
$(document).ready(function() { 
    $.getJSON( $("#json").html() , function(json) {
        $.each(json.data, function(index, value) { $('.data').append(value.a+'<br />'); } );
    });
});
</script>

<div class="data"></div>

{“数据”:[
{“a”:“b”},
{“a”:“c”}
]}
$(文档).ready(函数(){
$.getJSON($(“#json”).html(),函数(json){
$.each(json.data,函数(索引,值){$('.data').append(value.a+'
');}); }); });
$。getJSON使用GET HTTP请求从服务器加载JSON编码的数据。你不能像现在这样使用它

方法
$.getJSON()
旨在对Web服务器进行Ajax调用,而不是从页面上获取内容。试试这个:

$(document).ready(function() {
    var data = $.parseJSON($("#json").html());
    $.each(data.data, function(index, value) { $('.data').append(value.a+'<br />'); } );
});
$(文档).ready(函数(){
var data=$.parseJSON($(“#json”).html();
$.each(data.data,函数(索引,值){$('.data').append(value.a+'
');}); });
演示:


使用
$(“#json”).html()
将字段的内容作为字符串提供给您,然后将其传递给
$.parseJSON()
,以获取可以使用的对象。

出于好奇,为什么您要将json存储在页面上的
中,而不是将其作为JavaScript中的变量直接输入?