ajax received background data is displayed on html page

  • 2021-07-22 08:40:27
  • OfStack

Java code


 PrintWriter out=response.getWriter(); // Send character data to the client 
 response.setContentType("text/text"); // Set the content type and encoding of the request and response 
 response.setCharacterEncoding("UTF-8");
 JSONArray json = JSONArray.fromObject(newsList); // Will newsList Object to the json Object 
 String str = json.toString(); // Will json Object to a string 
 out.write(str); // Will str Character transfer to foreground  

Ajax code


 $(document).ready(function() {
 $.ajax({
 url : "newsservlet",// Request address 
 dataType : "json",// Data format  
 type : "post",// Request mode 
 async : false,// Whether to request asynchronously 
 success : function(data) { // How to Send Successfully 
 var html = "";
 for(var i=0;i<data.length;i++){ // Traversal data Array 
 var ls = data[i]; 
 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>";
 }
 $("#ulul").html(html); // In html Page id=ulul Displays in the label of html Content 
 },
})
})

HTML page

<ul id="ulul"></ul>

In ajax, "#" stands for id of 1 tag and "." stands for class of 1 tag

In the background of Java, setting the content type and encoding mode of request and response must be written before json object conversion string, otherwise it will cause json Chinese garbled code


Related articles: