在这段代码中,Jquery使用$ .when()进行两次调用$ .get()。使用JSON.parse()时会发生此问题。如果我进行一次调用,然后只调用一个变量,那就没问题,但是当两者都被调用时,好像JSON.parse()的执行被阻止了,并且控制台向我显示了这个错误:“Uncaught SyntaxError:Unexpected token&lt ;” in。
我怎么解决?谢谢你的帮助。这是代码:
function carica_commenti(id)
{
var pagina = $('#pagina'+id).val();
$.when($.get("/carica_commenti_ajax/"+id+"/"+pagina), $.get("/post/commenti/apprezzamenti_commenti")).done(function(commenti, app)
{
var commento = JSON.parse(commenti);
var apprezzamenti = JSON.parse(app);
var resultHtml = '';
$.each(commento, function(i, el)
{
resultHtml += "<div class='commento' id='commento"+ el.id_comments + "'>\
<a href='goak.it/utente/"+ el.id_user +"/1'>\
<img src='//goak.it/"+ el.percorso +"'width=30px and height=30px/>\
<strong>"+ el.nome +" "+ el.cognome +"</strong>\
</a>\
<span id='corpo-commento"+ el.id_comments +"'>"+ el.contenuto +"</span>\
<div class='post-modifica btn-group'> \
<button type='button' class='btn btn-post btn-default dropdown-toggle post-tasti-modifica tasto-commento' data-toggle='dropdown'>\
<span class='caret'></span>\
</button>\
<ul class='dropdown-menu' role='menu'>\
<li><a href='#' data-toggle='modal' data-target='#modifica-commento' class='modifica-commento' id='"+ el.id_comments + "'>Modifica Commento</a></li>\
<li><a href='#' data-toggle='modal' data-target='#cancella-commento' class='cancella-commento' id='"+ el.id_comments + "'>Cancella Commento</a></li>\
</ul>\
</div>\
</div>\
<div class='info-notifica data-commento'>\
<time class='timeago'> Adesso · </time>\
<a class='mi-interessa-commento' id='like_commento"+ el.id_comments + "' onclick='like_commento("+ el.id_comments +")' value='1'> Mi interessa </a>\
</div>";
});
$('#commentscontainer'+id).append(resultHtml);
});
var $input = $('#pagina'+id);
$input.val( +$input.val() + 1 );
}
答案 0 :(得分:0)
您的参数commenti
和app
确实是数组,但具有ajax响应的结构:[ data, statusText, jqXHR ]
。
因此,如果您要解析通话结果,则必须在JSON.parse()
上致电data
,而不是整个阵列。
See an example from jQuery's docs:
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
if ( /Whip It/.test( data ) ) {
alert( "We got what we came for!" );
}
});