jQuery中使用$.ajax跨域请求Servlet数据的实例

时间:2021-03-15 21:11:25

一、客户端代码

客户端运行地址:http://127.0.0.1:8020/Hungry_Project2/index.html,服务端地址为http://localhost:8080/HungryServer/GetAllTakeOutfoods,所以必须跨域请求。参考文章:http://blog.csdn.net/fullstackchenzf/article/details/68061584。

  其中dataType:'jsonp'和jsonp:'callback'是必须要配的值,表示是跨域请求数据,GetAllTakeOutfoods是一个用Java编写的Servlet。

   <script>
$(function(){
$.ajax({
type:"get",
url:"http://localhost:8080/HungryServer/GetAllTakeOutfoods",
async:true,
dataType:'jsonp',
jsonp:'callback',
success:function(data){
$.each(data, function(index,dom) {
//alert(dom['fName']);
var div=$("<div class='row'><div class='col-xs-5'><div style='margin-left: 15px;'><img src='img/"+dom['fImage']+"' class='img-rounded'/></div></div><div class='col-xs-7'><div style='margin-left: 15px;'><b>"+dom['fName']+"</b><span style='color: #35B3E4;'>&nbsp;&nbsp;&nbsp;来一份</span><br/>"+dom['fDescription']+"<br/><b>&yen;"+dom['fPrice']+"元</b></div></div></div><hr/>");
$("#content").append(div);
});
}
});
})
</script>

二、服务端

GetAllTakeOutfoods具体代码如下:

package cn.com.bochy.hungry.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import cn.com.bochy.hungry.biz.ITakeout_foodBiz;
import cn.com.bochy.hungry.biz.impl.Takeout_foodBizImpl;
import cn.com.bochy.hungry.entity.Takeout_food;
public class GetAllTakeOutfoods extends HttpServlet {
private static final long serialVersionUID = 1L;
ITakeout_foodBiz biz=new Takeout_foodBizImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
      String c=request.getParameter("callback");
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
     List<Takeout_food> lis=biz.getAlltakeoutFoods();
    JSONArray json=JSONArray.fromObject(lis);
    out.print(c+"("+json+")");
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 doGet(request, response);
}
}

参考文章:http://blog.csdn.net/fullstackchenzf/article/details/68061584