使用jquery ajax调用rest webservice?

我尝试了几个教程,使用jQuery ajax调用来调用rest web-service,但我没有得到响应。

但是当我直接在浏览器中访问url时,我得到了响应,但无法使用ajax调用获得相同的json响应,总是进入错误块。 (tomcat在端口8888上运行)

HTTP://本地主机:8888 / WebService_2 / REST / Web服务

Index.jsp文件。

     Insert title here    
$(document).ready(function(){ $("#submit").click(function(){ $.ajax({ type: "GET", dataType:"json", contentType: "application/json; charset=utf-8", url: "http://localhost:8888/WebService_2/rest/webservice", success: function(data1) { console.log("response:" + data1); }, error: function(jqXHR, textStatus, errorThrown) { console.log(' Error in processing!'); } }); }); });

WebSerivce类。

 package com.app.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/webservice") public class WebSerivce { @GET @Produces(MediaType.APPLICATION_JSON) public String getResponse(){ return "Web Service Response Call " ; } } 

web.xml中

  jersey-serlvet com.sun.jersey.spi.container.servlet.ServletContainer  com.sun.jersey.config.property.packages com.app.rest  1   jersey-serlvet /rest/*  

在谷歌之后得到答案…我已经使用谷歌jar进行JSON转换

的pom.xml

  com.google.code.gson gson 2.2.4  

WebService.class

 import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @Path("/webservice") public class WebSerivce { @GET @Produces(MediaType.APPLICATION_JSON) public Object getResponse(){ //firstName,LastName,Age,Id Student std1 = new Student("ik","test",22,2); Student std2 = new Student("John","Vector",23,3); Student std3 = new Student("iks","Roy",25,4); List stuList = new ArrayList(); stuList.add(std1); stuList.add(std2); stuList.add(std3); Gson gson = new GsonBuilder().create(); return gson.toJson(stuList); } } 

的index.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>     Insert title here