简体   繁体   中英

Jquery ajax call returns error when the rest service is returning a string

Trying to send a simple text from my rest service and read it using ajax call. Found many answers about jsonp and cross browser compatibility, tried crossdomain too.

Here is the rest service: Trimmed everything down to send only a simple string.

@GET
@Path("/getcontents2")
@Produces({MediaType.TEXT_PLAIN})
public String getContents2(@QueryParam("name") String msg) {
  return "abc";
}

The ajax call:

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    url: 'http://metrics/getcontents2?name=Work/loc.txt',
    crossDomain: true,
    async: false,
    dataType:'html',
    success: function (data) {
      console.log(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
      console.log(xhr.status);
      console.log(thrownError);
      console.log(xhr.responseText);
      console.log(xhr);
    },
  });
});

The browsers opens up the string as is. I guess something is really wrong in the jquery script.

Error on Firebug:

GET http://metrics/getcontents2?name=Work/loc.txt 200 OK 4ms    
0 
(an empty string) 
(an empty string) 
Object { readyState=0, status=0, statusText="error"} 

Fixed it!

It was because my server was not supporting cross-domain. Configured it will corsfilter and it worked like a charm!

try setting your datatype to text jsonp

dataType: 'jsonp',

http://api.jquery.com/jQuery.ajax/

You will have to do one of two things to go with this to resolve the error further;

  1. making changes on the server side to pass the data back as json and not as text
  2. retun the string encoded in json return "{"text":"abc"}"; //or something like this return "{"text":"abc"}"; //or something like this

Why?

jquery cross-domain requests are only allowed for dataTypes "script" and "jsonp".

I have updated your fiddle it still throws an error but that is related to a parse json error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM