I am getting JSON data for a .getJSON function for Jquery. I am thinking of using .text to make the data safe (I believe this is the proper thing to do). I have tested and the JSON is correct.
Here is the script I am working on:
var firstpost = 0;
var firstrun = 0;
var lastpost = 0;
^ Global vars
$.getJSON('chatget.php', {
'chatroomid' : '<?php echo $chatroomid; ?>',
'firstpost': firstpost,
'lastpost': '1'},
function(data) {
var template = '<div id="_ID_" class="chatpost"> <div><b>_NAME_ </b> <a href="_URL_"> _USERNAME_ </a> _DATETIME_</div> <div><em>_TARGETS_</em></div> <div>_TEXT_</div> </div>';
var appendhtml ='';
var datarows = data['New'].length;
lastpost = data['New'][datarows]['CPid'];
// Each row processor
$.each(data['New'], function(index, col){
// Get initial data
if (firstrun == 0){
firstpost = col.CPid;
firstrun = 1;}
// process targets
if(col.Targets !== null){
var target = col.Targets.split(',');
var trow = target.length;
var targets = '';
for (var i=0, len=target.length; i<len; i++){
targets = targets + '@' + target[i] + ' ';}
}else {var targets = '';};
// Append data to chatroom
var cpid = $.text(col.CPid);
var name = $.text(col.Name);
var username = $.text(col.Username);
var url = $.text(col.Url);
var text = $.text(col.Text);
var datetime = $.text(col.Datetime);
var targets = $.text(targets);
appendhtml = template.replace('_ID_',cpid).replace('_NAME_',name).replace('_USERNAME_',username).replace('_URL_',url).replace('_TEXT_',text).replace('_DATETIME_',date).replace('_TARGETS_', targets);
$('#chatroom').append(appendhtml);
});
} // End Data function
) // End Get Json
For some reason since I changed some stuff in this code it is crashing firebug so either I found a bug in firebug or I did something very wrong in the coding. I don't think I am using $.text correctly...
Also I am trying to get the last value in the data['New'] object/array. .length doens't seem to be working.
var datarows = data['New'].length;
lastpost = data['New'][datarows]['CPid'];
This is my first javascript/Jquery program so if you see something wrong in the code please tell me.
For best practice, encapsulate your code within an anonymouse wrapper function so that any functions or variables you create/used is inaccessible to outside environtment.
(function(){
//your code
}())
NOTE: Google, jquery, etc all follow this system of practice!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.