使用JQuery Ajax调用来调用Rest Web服务,Web服务返回JSON字符串 [英] Calling Rest webservice using JQuery Ajax call , web service is returning JSON string

查看:145
本文介绍了使用JQuery Ajax调用来调用Rest Web服务,Web服务返回JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了一个Rest Web Service:

I have made a Rest Web Service:

package org.jboss.samples.rs.webservices;


import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;



@Path("/MyRESTApplication")
public class HelloWorldResource {


    @GET()
    @Produces("application/json")
    @Path("/dealInfo/{dealId}")
    public String sayHello(@PathParam("dealId") int dealId) {
        System.out.println("dealid......"+dealId);
        switch(dealId) {
        case 1 :System.out.println("employee id.....");
            return "{'name':'George Koch', 'age':58}";
        case 2:
            return "{'name':'Peter Norton', 'age':50}";
        default:
            return "{'name':'unknown', 'age':-1}";
    } // end of switch

    }
}

当我去浏览器&在地址栏中输入以下内容:

When I go to internet explorer & type this in the address bar:

http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2

它给了我

{'name':'Peter Norton', 'age':50}

但是当我在JQuery方法中使用ajax调用进行调用时.例如

But when I call it using an ajax call in a JQuery method. e.g.

$.ajax({  
           type: "GET",  
           url: "http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2",  
           data: "",  
           success: function(resp){  
             // we have the response  
             alert("Server said123:\n '" + resp + "'");  
           },  
           error: function(e){  
             alert('Error121212: ' + e);  
           }  
         });

我在通话中收到错误消息.

I am getting an Error in this call.

当我在IE中使用F12进行调试时,我也会得到关注

When I am debugging using F12 in IE, I am getting following as well

"Invalid JSON: {\'name\':\'Peter Norton\', \'age\':50}"

有人可以告诉我我的通话可能是什么问题.

推荐答案

我认为您没有返回有效的json:请尝试以下操作:

I think that you are not returning a valid json: try something like:

  return  "{\"name\":\"unknown\", \"age\":-1}"

因此

{
    "name": "unknown",
    "age": -1
}

是有效的JSON(您必须使用",而不是'),而不是

is a valid JSON (You must use ", not ') while this is not

{
    'name': 'unknown',
    'age': -1
}

您还应该指定数据类型

 $.ajax({  
       type: "GET",  
       url: "http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2",  
       dataType: "json",  
       success: function(resp){  
         // we have the response  
         alert("Server said123:\n '" + resp.name + "'");  
       },  
       error: function(e){  
         alert('Error121212: ' + e);  
       }  
     });

这篇关于使用JQuery Ajax调用来调用Rest Web服务,Web服务返回JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆