2017-03-03 135 views
1

我有这样的代码,我不知道什么是错的

$(document).ready(function() { 
 
    $.ajax({ 
 
    type: 'GET', 
 
    url: 'data.json', 
 
    dataType: 'json', 
 
    success: jsonParser 
 
    }); 
 
}); 
 

 
$(".btn_val1").click(function() { 
 
    function jsonParser(json) { 
 
    $.getJSON('data.json', function(data) { 
 
     $.each(data.dt.ld, function(k, v) { 
 
     var title = v.titleContent; 
 
     var img = v.image; 
 
     var txt = v.textContent; 
 
     $('.information_g').append('<p>' + txt + '</p>'); 
 
     }); 
 
    }); 
 
    } 
 
});

我运行该脚本,我得到这个错误后,我不知道是什么问题:

Uncaught ReferenceError: jsonParser is not defined

+0

jsonParser被点击处理程序中作用域? –

回答

4

问题是因为您仅在.btn_val1点击处理程序的范围内定义jsonParser()函数。它需要在您拨打$.ajax的范围内。

另请注意,你的逻辑有点奇怪。您正在对data.json进行AJAX调用,然后在该请求的success的处理程序中再次进行相同的调用。我建议您从jsonParser()中删除$.getJSON()来电。试试这个:

function jsonParser(data) { 
    $.each(data.dt.ld, function(k, v) { 
    var title = v.titleContent; 
    var img = v.image; 
    var txt = v.textContent; 
    $('.information_g').append('<p>' + txt + '</p>');  
    }); 
} 

$(document).ready(function() { 
    $.ajax({ 
    type: 'GET', 
    url: 'data.json', 
    dataType: 'json', 
    success: jsonParser 
    }); 
}); 

$(".btn_val1").click(function() { 
    // do something when this button is clicked... 
}); 
1

jsonParser里面$(".btn_val1").click所以这是一个点击后才能访问。所以,你需要将它移出点击处理程序的范围。

function jsonParser(json) { 
    $.getJSON('data.json', function(data) { 
     $.each(data.dt.ld, function(k, v) { 
     var title = v.titleContent; 
     var img = v.image; 
     var txt = v.textContent; 
     $('.information_g').append('<p>' + txt + '</p>'); 
     }); 
    }); 
    } 
0

您尝试在定义它之前传递函数。试试这个:

function jsonParser(data) { 
 
    $.each(data.dt.ld, function(k, v) { 
 
    var title = v.titleContent; 
 
    var img = v.image; 
 
    var txt = v.textContent; 
 
    $('.information_g').append('<p>' + txt + '</p>'); 
 
    }); 
 
} 
 

 
$(document).ready(function() { 
 
    $.ajax({ 
 
    type: 'GET', 
 
    url: 'data.json', 
 
    dataType: 'json', 
 
    success: jsonParser 
 
    }); 
 
}); 
 

 
$(".btn_val1").click(function() { 
 
    // should it also call ajax request? 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>