开发者

JSON String parsing in javascript?

I'm using ajax to make a request on a servletand receive json String

servlet code //Server Side

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        try { 
        ArrayList<SearchedCourse> searchedCourses = null;
        int semesterNo = request.getParameter("semesterNo");
        searchedCourses = //Using function to retrieve data from DB and return an ArrayList 
        String courses = gson.toJson(searchedCourses);
        out.write(courses);
                }
            }
        }  finally {
            out.close();
        }
    }

and this is the return json string "I used firebug to copy it"

[{"courseNumber":1619,"courseNo":"HADTA1100","courseName":"قرآن كريم (1) جزء عم","courseExamDate":"Aug 21, 2011","courseExamTimeFrom":"14:30","courseExamTimeTo":"15:30"},{"courseNumber":1663,"courseNo":"HADTB1100","courseName":"قرآن كريم (2) جزء تبارك","courseExamDate":"Aug 23, 2011","courseExamTimeFrom":"14:30","courseExamTimeTo":"15:30"}]

I use the code below to parse the Json string at the client side

  jQuery.ajax({
    url: 'auth/json/AvailableCoursesGetter',
    type: "GET" ,
    dataType: "json",
    data: {
        'semesterNo': 20112
    },
    success: function(data) {
 开发者_运维百科       for (var i = 0, len = data.length; i < len; i++) {
             document.write(data[i].courseNumber);
        }

    }
});

it works fine on Mozilla FireFox4, but on Google Chrome and IE it doesn't display any thing

any help ?


I just saw that you output the following header in your servlet:

response.setHeader("Content-Type", "text/html;charset=UTF-8");

Try changing the content type to application/json.


@Eli is correct about using the for in being a bad idea, but it seems to me that the code should be working. The following jsFiddle works in IE9 : http://jsfiddle.net/shaneblake/arhB7/

Are you sure the data is comming back in the correct format and not as a string? have you tried using JSON.parse(data) to make sure?


It is considered bad practice to iterate over an array using the for in syntax. Try this instead:

for (var i = 0, len = data.length; i < len; i++) {
    console.log(data[i].courseNumber);
}

If your page in any way has extended the Array prototype, then using for in will cause your script to iterate over those extended properties, and if those are being hit before your actual values, it will most likely cause an error. The best way to avoid this is to use a traditional for loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜