成功内部循环变量:在ajax中调用JS

时间:2017-04-12 04:58:58

标签: javascript jquery ajax

您好我整天都在寻找解决方案,但还没弄明白。我有一个$ .ajax调用,我正在循环并打印出我想要的值。已经完成了,我的问题是我分配的var数组但是在显示之前无法操作它。在成功函数内部,我启动一个for循环并分配var数组值,如果我不操作它们,程序会继续,但是当我添加一些操作时它会被卡住。我正试图用_ chars替换\ chars但是titl [i]没有任何操作类型。我对JS很新,所以可能会有一些我缺少的东西,真的会有一些见解!干杯。

  success: function (x) {
   var titl = [];
   var len = x.query.search.length;

   $('.entries').html("");


   for (var i = 0; i < len; i++) {

    titl[i] = x.query.search.title.split(' ').join('_');
    //want to manipulate titl[i] here *************************
     $('.entries').append('<div class="row"><div class="col-md-12">' +  x.query.search[i].title + '<br>' + x.query.search[i].snippet + '</div></div>'); 

1 个答案:

答案 0 :(得分:0)

请检查下面的代码并附上评论。

success: function (x) {
    var titles = [], // Do you need them as an array?
        search = x.query.search,
        searchItem,
        title = '',
        len = search.length,
        $entries = $('.entries'), // Keep the reference in a variable
        html = [];

    // You can just remove all content of entries
    $entries.empty();

    for (var i = 0; i < len; i++) {
        // Missing the search index?
        searchItem = search[i];

        // Use push instead and keep title as reference so you can use later on
        title = searchItem.title.split(' ').join('_');
        titles.push(title);

        // Don't append just yet
        html.push('<div class="row"><div class="col-md-12">');
        html.push(title);
        html.push('<br>');
        html.push(searchItem.snippet);
        html.push('</div></div>');
    }

    // Instead append, just use HTML
    $entries.html(html.join(''));
}