The ajax receiving background data is displayed on the html page and the ajax receiving background page
Java code
1 PrintWriter out = response. getWriter (); // send the string data 2 response to the client. setContentType ("text/text"); // set the request and response content type and encoding method 3 response. setCharacterEncoding ("UTF-8"); 4 JSONArray json = JSONArray. fromObject (newsList); // convert newsList object to json object 5 String str = json. toString (); // converts a json object to a string of 6 out. write (str); // transmit str characters to the foreground
Ajax code
1 $ (document ). ready (function () {2 $. ajax ({3 url: "newsservlet", // request address 4 dataType: "json", // data format 5 type: "post", // Request Method 6 async: false, // asynchronous request 7 success: function (data) {// how to send successfully 8 var html = ""; 9 for (var I = 0; I <data. length; I ++) {// traverse the data array 10 var ls = data [I]; 11 html + = "<li> <a href = 'second page text.html? Newsid = "+ ls. news_id + "'class = 'infnews _ wrod_a '> <span>" + ls. news_name + "</span> </a> <span class = 'date'>" + ls. news_time + "</span> </li>"; 12} 13 $ ("# ulul" ).html (html ); // display html content 14}, 15}) 16} in the tag id = ulul of the html page })
HTML page
1 <ul id="ulul">2 3 </ul>
In ajax, "#" indicates the id of a tag, and "." indicates the class of a tag.
In the Java background, the content type and encoding method of the request and response must be set before the json object conversion string. Otherwise, json Chinese garbled characters may occur.