jQuery .map()函数的类型和格式问题

时间:2012-12-20 01:58:45

标签: javascript json jquery types jquery-ui-autocomplete

我正在尝试将第二个数据源中的选择插入到“自动完成”下拉列表中。第一和第二源提取都是通过ajax。我精心编写了一个JSON数组,用于将2d源数据插入到Autocomplete的下拉列表中。它通过了jsonLint测试。格式如下:

[{"label":"New York, Bronx, Bronx County, New York, United States","value":"Bronx, Bronx County, New York, United States"},
{"label":"New York, Brooklyn, Kings County, New York, United States","value":"Brooklyn, Kings County, New York, United States", }]

我在创建代码以将变量数据放入该类型和格式时遇到了很大的麻烦。数据库当前包含JSON字符串。我使用PHP的json_encode()来创建传递给浏览器的数据对象。数据库条目可以更改,但现在看起来像:

"label":"New York, Bronx, Bronx County, New York, United States","value":"Bronx, Bronx County, New York, United States"

似乎1. JSON字符串不会更改为对象,并且2.某些外来的未知字符会以某种方式插入。但是,我是一个新手,特别是功能和对象。这是jQuery / Javascript,以及关于各点数据状态的一些评论。

var boroughData = function() {
    $.ajax({
        //normal stuff like url:, dataType:, etc. It works.
        success: function (data){
            boroughData = $.map( data, function (item){
                //data is JSON, but info inside extra " ", like Object { boroughString=""label":"Dallas, Cockre..., Texas, United States""}
                // # response like [{"boroughString":"\"label\":\"Dallas, Cockrell Hill, Dallas County, Texas, United States\", . . ."}]
                return item.boroughString;//returns JSON strings, not objects, in an array
            });
            alert(jQuery.isArray(boroughData)  + "|bD1"); //true
            console.log(boroughData); //array containing JSON strings in red
        } //closes success: for boroughData
    }); //closes ajax for boroughData
}(); //closes boroughData and (); executes it
alert(jQuery.isArray(boroughData)  + "|bD2"); //false
alert(boroughData + "|bD3"); //"label":"Dallas, Cockrell Hill, Texas", "value":"Dallas, Cockrell Hill, Texas","label":"Dallas, Downtown Dallas, Texas", "value":"Dallas, etc.
alert(JSON.parse(boroughData) + "|bD4");//SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

请注意,bD1处的isArray测试为true,而bD2处的isArray测试为false,它们之间唯一发生的事情是关闭函数和ajax。另请注意带有散列#标记的注释行,用于记录看似额外的“”标记。

如何让boroughData函数输出一个JSON数组,其格式与我在上面第一个代码框中显示的格式相同?请具体说明您的建议和代码。我是新手,不遵循一般说明。

1 个答案:

答案 0 :(得分:0)

IMO您的函数不返回值。 我不确定你的方式是否真的能够正常执行,但请相信:)

    function boroughData () {
    $.ajax({
        success: function (data){
            boroughData = $.map( data, function (item){
                return item.boroughString;//returns JSON strings, not objects, in an array
            });
            alert(jQuery.isArray(boroughData)  + "|bD1"); //true
            console.log(boroughData); 
        } 
    });
    return boroughData; // it's not good practice to use the same name for local variable... 
    }(); 
    alert(jQuery.isArray(boroughData)  + "|bD2"); //false
    alert(boroughData + "|bD3");
    alert(JSON.parse(boroughData) + "|bD4");