今天打算尝试一次以对象方式传入参数到另一个方法中。但是出了点问题。先上代码
function initIpRule_callback(data){
var count = data.count;
totalpage = data.totalPage;
var ipRuleList = data.ipRuleList;
var length = ipRuleList.length;
var html = '';
$("#listTable").empty();
for(var i=0; i<length; i++){
html += '<tr>';
html += '<td width="45px" class="border-r t-a-c">'+ipRuleList[i]["exd_id"]+'</td>';
html += '<td width="160px" class="border-r ti-20 t-a-c">'+ipRuleList[i]["port_outer"]+'</td>';
html += '<td width="160px" class="border-r ti-20 t-a-c">'+ipRuleList[i]["ip_addr_outer"]+'</td>';
html += '<td width="80px" class="border-r ti-20 t-a-c">'+ipRuleList[i]["protocol_name"]+'</td>';
html += '<td width="160px" class="border-r ti-20 t-a-c">'+ipRuleList[i]["ip_addr_inner"]+'</td>';
if(ipRuleList[i]["used_status"] == 0)
html += '<td width="110px" class="border-r ti-15 t-a-c">启动</td>';
else if(ipRuleList[i]["used_status"] == 1)
html += '<td width="110px" class="border-r ti-15 t-a-c">停用</td>';
html += '<td width="123px" class="operate ti-15 po-re t-a-c">';
html += '<a class="change-ry table-link wp-45 ml-8" '+
'οnclick="modifyRule_pre('+ipRuleList[i]+')">修改</a>';
html += '<a class="dele-ry dele-bm table-link wp-45" οnclick="delRule('+ipRuleList[i]["exd_id"]+');">删除</a>';
html += '</td>';
html += '</tr>';
}
$("#listTable").append(html);
}
接收的函数。只是简单地接收传入的对象,并且把对象中的两个属性显示出来。
function modifyRule_pre(ipRule){
console.log(ipRule);
alert(ipRule["port_outer"] + "===" + ipRule.ip_addr_outer);
}
在第一段代码中的“修改”那个地方,本来是要把循环遍历出来的这一行记录作为一个对象传给下一个方法。
但是一开始这样写是不行的。然后我在这个对象的前后加了个引号,成了这样
html += '<a class="change-ry table-link wp-45 ml-8" '+
'οnclick="modifyRule_pre('\'+ipRuleList[i]+'\')">修改</a>';
这样接受的时候,看到的却是一个[Object Object]的字符串了。我遍历了它,出来的东西就是将object单词拆成字符打印出来。
然后网上搜了搜,有人建议将对象变成一个字符串传递,使用JSON.stringify(ipRuleList[i])方法。
然后我试了一下,在接收函数那里看到的东西是这样的。
这是因为我的这个对象中(json对象)都是以双引号包围起来的键和值,如下所示
{"exd_id":"1","ip_addr_outer":"172.xx.xx.xx","protocol_name":"SSH"}
就是这些双引号,在拼接的时候被错误的分了组。如下图红框所示。
所以传递到modify_pre函数的时候,相当于只传了半个大括号过去。这就是上面报错的原因。
所以思路变为怎么将双引号失效或者进行转义。尝试如下
html += '<a class="change-ry table-link wp-45 ml-8" '+
'οnclick="modifyRule_pre('+JSON.stringify(ipRuleList[i]).replace(/"/g,""")+')">修改</a>';
但是这样转义后依然出问题。根本原因貌似是因为我的这个json对象中,键值中的数字也用双引号包围起来了。
这样双引号被转义后的东西与数字拼成了一个新的东西。
然后考虑是否转移符用的不好,搜了搜,改成了"来对双引号转义。终于出来了想要的效果了。
附上一个不错的网站,叫做“在线工具”,里面有转移符、ASCII码对照表等好东西,可以参考。