[英]Javascript/Jquery Prevent injections from executing code
I am getting JSON data for a .getJSON function for Jquery. 我正在为Jquery的.getJSON函数获取JSON数据。 I am thinking of using .text to make the data safe (I believe this is the proper thing to do).
我正在考虑使用.text来确保数据安全(我相信这是正确的做法)。 I have tested and the JSON is correct.
我已经测试过,并且JSON是正确的。
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. 由于某种原因,由于我更改了这段代码中的某些内容,因此它使Firebug崩溃,因此我在Firebug中发现了一个错误,或者在代码中做错了什么。 I don't think I am using $.text correctly...
我认为我没有正确使用$ .text ...
Also I am trying to get the last value in the data['New'] object/array. 我也试图获取data ['New']对象/数组中的最后一个值。 .length doens't seem to be working.
.length似乎不起作用。
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. 这是我的第一个javascript / Jquery程序,因此如果您在代码中看到错误,请告诉我。
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! 注意:Google,jquery等均遵循此练习系统!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.