[英]I have this code and I have no idea what is wrong
$(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>'); }); }); } });
運行腳本后,出現此錯誤,我不知道問題出在哪里:
未捕獲的ReferenceError:未定義jsonParser
問題是因為僅在.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...
});
您的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>');
});
});
}
您嘗試在定義之前傳遞功能。 嘗試這個:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.