0

我想传递 json 对象的一些元素,例如 objson.post.mypost[i].idpost 作为 javascript 函数中的参数,这是我的脚本:

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp1=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange=function()
{
    if (xmlhttp1.readyState==4 && xmlhttp1.status==200)
    {
        var txttmp2 = xmlhttp1.responseText;
        var obj2 = $.parseJSON(txttmp2);
        var text1= document.getElementById("tabs-Mil");
        var objln=obj2.post.mypost.length;
        //alert(objln+"");
        for(var counter=0;counter<objln;counter++)
        {
            text1.innerHTML+=" '"+obj2.post.mypost[counter].status+"' @ <a href='#'>"+obj2.post.mypost[counter].namalokasi+"</a>&nbsp;on "+obj2.post.mypost[counter].tanggal+"<br/><a href='#' onclick='addcomment("+obj2.post.mypost[counter].idpost+","+localStorage.loggeduser+")'>comment</a><hr width='80%' align='left'><br/>";
            text1.innerHTML+="<span id='comments' name='comments'></span>";
        }
    }
 }
xmlhttp1.open("GET","http://localhost:280/finaltask/forjson.php?tmpid="+iduser+"&proses=showpost",true);
xmlhttp1.send();

function addcomment(idcheckin,iduser)
{
    $("#formcomment").show();
    var detpost=document.getElementById("detail-post");
    alert(idcheckin+"/"+iduser);
}

我已经通过了 json 对象元素: onclick='addcomment("+obj2.post.mypost[counter].idpost+","+localStorage.loggeduser+")'

但是当函数执行时(函数addcomment(idcheckin,iduser)),据说'idcheckin'是'未定义'.....

谁能帮我 ?

4

2 回答 2

0

Do not attach complex event handler by concating string, use library like jQuery:

$("<a></a>").text("Hello").click(function () {
    addComment(obj.post.mypost[counter].idpost, ...);
})
于 2012-06-08T02:35:29.567 回答
0

确保您的返回结果符合预期。您应该检查 idpost 是否有效,考虑在循环开始时添加日志记录。

    for(var counter=0;counter<objln;counter++)
    {
        console.log('loop results ' + counter + ': ' + JSON.stringify(obj2.post.mypost[counter])); // confirm output of selected element
        alert('idpost: ' + obj2.post.mypost[counter].idpost); // Check result
        text1.innerHTML+=" '"+obj2.post.mypost[counter].status+"' @ <a href='#'>"+obj2.post.mypost[counter].namalokasi+"</a>&nbsp;on "+obj2.post.mypost[counter].tanggal+"<br/><a href='#' onclick='addcomment("+obj2.post.mypost[counter].idpost+","+localStorage.loggeduser+")'>comment</a><hr width='80%' align='left'><br/>";

也考虑改变:

addcomment("+obj2.post.mypost[counter].idpost+","+localStorage.loggeduser+")

至:

addcomment(\""+obj2.post.mypost[counter].idpost+"\",\""+localStorage.loggeduser+"\")
于 2012-06-08T03:01:57.003 回答