1

我目前正在做一个项目,我需要将一些旧代码转换为 json 对象。我们从 sql 查询中获取结果集,并将它返回的类别作为 json 返回。我不太精通javascript,更不用说json了,所以我不确定最简单的方法是什么。这是我需要更改为 JSON 的函数:

function createOutputCategories(){
try
    {
        output = 
                "<html>" +
                "<head>" +
                "<title>" +
                "You can find it!" +
                "</title>" +
                "</head>" +
                "<body bgcolor='#CED3F3'>" +
                "<a href='" + url + "file.xsjs?parent=1'>" +
                "</a>" +
                "<br><br>";
        if(parent === "1"){
            output = output + "<h3><font color='#AAAAAA'>Home</font>";
        }else{
            output = output +"<a href='javascript:history.back()'>" +
            "<h3>Back";
        }
        output = output +
                "</h3>" +
                "</a>" +
                "<h1>" +
                "Categories:" +
                "</h1>";

        while(rs.next()){
            if(rs.getString(3) === 0 || rs.getString(3) === null || rs.getString(3) === undefined || rs.getString(3) === "0" ){
                output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(2) + "</a>";
            }else{
                output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(3) + "</a>";
            }
        }
}catch(Exception){
    $.response.contentType = "text/plain";
    $.response.setBody( "Failed to retreive data" );
    $.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}

这是我到目前为止所拥有的,但我没有返回有效的 JSON 对象:

function createOutputCategories(){

try{
    output = 
        "category: {name = \"" + parent + "\"; description = \"\"}";

    output = output +
        "subcategories: [ ";

    while(rs.next()){
        output = output + 
            "{ catid = \"" + rs.getString(1) + "\"; catname = \"" + rs.getString(2) + "\"; altname = \"" + rs.getString(3) + "\"; description = \"" + rs.getString(4) + "\"}";
        }
    output = output +
        "];";
    }
catch(Exception){
    $.response.contentType = "text/plain";
    $.response.setBody( "Failed to retreive data" );
    $.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}

如果我需要提供其他任何东西,请告诉我!谢谢!

4

1 回答 1

3

您想将 javascript 对象输出到字符串吗?

构造对象:

var category=new Object();
category.name="Name";
category.description="My lovely description";
category.subcategories=[];

var subCat=new Object();
subCat.catid=1;
subCat.catname="My subcat";

category.subcategories.push(subCat);

或者,您可以使用文字构造对象:

 var category={
     name:"Name",
     description:"My lovely description",
     subcategories:[
         {catid:1,catname:"My subcat"}
     ]
 };

然后将对象作为字符串返回。

return JSON.stringify(category);

如果您需要更多帮助,请参考 Javascript 对象:http: //www.w3schools.com/js/js_objects.asp

于 2013-07-03T10:02:29.053 回答