使用Ajax的“意外的输入结束”

I am building a thread-messaging system. I used AJAX to send the parent_id to the php file which retrieved the thread (many messages with the same parent_id)

in the ajax, I send the parent_id

data:{
    parent_id: $(this).data('id'),
    ajax: 'true'
},

I use this parent_id in the php file using a query which retrieves some rows and I pass them back using this :

$ret_msg_query_result=mysql_query($retrive_query);
while ($retrieved_msg_fetched=mysql_fetch_assoc($ret_msg_query_result))
{
echo json_encode($retrieved_msg_fetched) . "
";    
}

and then back to Ajax:

$(document).ready(function() { 
    $(".msgsRow li.msg_subject,.msgsRow li.msg_content").click(function() { 
        $.ajax({ 
            type: 'POST',
            url: AJAX_URL+"front/RetrieveMsg.php", 
            data:{ parent_id: $(this).data('id'), ajax: 'true' }, 
            success: function(data) { 
                         var strLines = data.split("
"); 
                         for (var i in strLines) { 
                             var obj = JSON.parse(strLines[i]); 
                             console.log(obj.id); 
                         }
                     } 
            }); 
        }); 
     });

I got this way (of splitting) to convert each row into an object from a post here on Stackoverflow Sending/Parsing multiple JSON objects

The function works right retrieving the ids of messages and even retrieving the full row. But I get

"Uncaught SyntaxError: Unexpected end of input "

and it points to the line before console.log(obj.id);

I searched StackOverflow for this error and it usually appears for missing a closing parenthesis but I can'd find any.

Thanks,

You are missing a } on in this function

success: function(data){
                var strLines = data.split("
");
                for (var i in strLines) {
                    var obj = JSON.parse(strLines[i]);
                    console.log(obj.id);
                **}**
            }

NOTE: remove the 4x*, those should not be there :)

That should fix it!

I figured out the problem ... It's because I am splitting using "/n" which makes the strLines be something like {row},{row},{row},

The comma in the end causes the unexpected end. So, I used a counter to check the number of row, if it's the last, then don't insert "/n"

$counter=1;

while ($retrieved_msg_fetched=mysql_fetch_assoc($ret_msg_query_result))
{
    if ($counter==mysql_num_rows($ret_msg_query_result))
    {
    echo json_encode($retrieved_msg_fetched);
    }
    else{
    echo json_encode($retrieved_msg_fetched) . "
";
    $counter++;
    }   
}

Thanks Limelights for your help too :)

I got this when I forgot to return something from my php-script when it worked fine. I just added something like this:

die (json_encode (array ('reponse'=>'Your script worked fine')));

at the end of my php-script, and that solved it. You can also use 'response' to check it it worked fine.