0

好的,我正在将数据库调用中的几年序列化为 json 对象。该对象是 web 服务对第一个 ajax 调用的响应。我的 javascript 错误控制台在它应该反序列化的行上抛出一个错误。我试图找出问题所在。

更新:

此代码有效,感谢 Jussi Kosunen

    $.ajax(
        {
            type: "POST",
            url: "default.aspx/HelloWorld",
            dataType: "json",
            data: "{name:'" + name + "'}",
            contentType: "application/json; charset=utf-8",
            success: function (msg) {

                //parse the object into something useable.
                var stringarray = JSON.parse(msg.d);

                //empty the results for next time around.
                 $('#year').empty();
                 for (index in stringarray) {
                    $('#year').append('<option>' + stringarray[index] + "</option>");


                    alert(stringarray[index]);

                }

这是将列表序列化为 json 对象的 C#;

    [WebMethod]
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
    public static string HelloWorld(string name)
    {
        string splitme = "USE VCDB SELECT DISTINCT YearID  FROM BaseVehicle";
         DataTable dt =  getDataTable(splitme);
         List<string> ids = new List<string>();
         foreach (DataRow row in dt.Rows)
         {
            ids.Add(row.ItemArray[0].ToString());

         }
        JavaScriptSerializer js = new JavaScriptSerializer();

        string x =js.Serialize(ids);

        return x;
    }

现在当我进入调试。这是 C# 返回的字符串。

     [\"1896\",\"1897\",\"1898\",\"1899\",\"1900\",\"1901\",\"1902\",\"1903\",\"1904\",\"1905\",\"1906\",\"1907\",\"1908\",\"1909\",\"1910\",\"1911\",\"1912\",\"1913\",\"1914\",\"1915\",\"1916\",\"1917\",\"1918\",\"1919\",\"1920\",\"1921\",\"1922\",\"1923\",\"1924\",\"1925\",\"1926\",\"1927\",\"1928\",\"1929\",\"1930\",\"1931\",\"1932\",\"1933\",\"1934\",\"1935\",\"1936\",\"1937\",\"1938\",\"1939\",\"1940\",\"1941\",\"1942\",\"1943\",\"1944\",\"1945\",\"1946\",\"1947\",\"1948\",\"1949\",\"1950\",\"1951\",\"1952\",\"1953\",\"1954\",\"1955\",\"1956\",\"1957\",\"1958\",\"1959\",\"1960\",\"1961\",\"1962\",\"1963\",\"1964\",\"1965\",\"1966\",\"1967\",\"1968\",\"1969\",\"1970\",\"1971\",\"1972\",\"1973\",\"1974\",\"1975\",\"1976\",\"1977\",\"1978\",\"1979\",\"1980\",\"1981\",\"1982\",\"1983\",\"1984\",\"1985\",\"1986\",\"1987\",\"1988\",\"1989\",\"1990\",\"1991\",\"1992\",\"1993\",\"1994\",\"1995\",\"1996\",\"1997\",\"1998\",\"1999\",\"2000\",\"2001\",\"2002\",\"2003\",\"2004\",\"2005\",\"2006\",\"2007\",\"2008\",\"2009\",\"2010\",\"2011\",\"2012\",\"2013\"]

大丑弦

4

1 回答 1

1

当您传递dataType: "json"到您的$.ajax呼叫时,它会自动解析您的 JSON。

于 2013-08-21T21:29:55.443 回答