开发者

Retrieve plain text with jquery ajax and convert to JSON

Update: the following works fine in IE8, but data comes back null in firefox:

$.getJSON('myUrl/solr/select/?q=citystate%3ASea*&version=2.2&start=0&rows=3&indent=on&wt=json&fl=citystate', function(data) {
  alert(data.response.docs[0].citystate);
});

I have a jetty server that generates json data as plain text - here are what the headers look like:

Last-Modified   Wed, 06 Oct 2010 23:22:27 GMT
Etag    "OTI5YWMzYzFkNDgwMDAwMFNvbHI="
Content-Type    text/plain; charset=utf-8
Content-Length  565
Server  Jetty(6.1.3)

Here is an example of the output:

{
 "responseHeader":{
  "status":0,
  "QTime":1,
  "params":{
    "fl":"citystate",
    "indent":"on",
    "start":"0",
    "q":"citystate:Sea*",
    "wt":"json",
    "version":"2.2",
    "rows":"10"}},
 "response":{"numFound":233,"start":0,"docs":[
    {
     "citystate":"Seaboard, AL"},
    {
     "citystate":"Seale, AL"},
    {
     "citystate":"Seacliff, AL"},
    {
     "citystate":"Sealy Springs, AL"},
    {
     "citystate":"Searcy, AL"},
    {
     "citystate":"Searight, AL"},
    {
     "citystate":"Searles, AL"},
    {
     "citystate":"Seasha, AL"},
    {
     "citystate":"Searcy, AR"},
 开发者_C百科   {
     "citystate":"Seaton, AR"}]
 }}

I want to retrieve this data using a jquery ajax call like this:

$.ajax({
  type: "GET",
  url: "myUrl/?q=citystate%3ASea*&version=2.2&start=0&rows=10&indent=on&wt=json&fl=citystate",
  dataType: "json",
  contentType: "text/plain; charset=utf-8",
  success: function(data, textStatus){
    alert("data: " + data);
  },
  error: function(data){
    alert("error");
  }
});

However, the result I get back is always null. What am I doing wrong?


If you can't get your server to send proper Content-type header (ie. application/json or text/javascript) you should just expect plain text dataType: 'text' and evaluate it.

function(data){
    eval('var data = ' + data + ';');
    // Rest of your code
}


Not sure if it's the root cause of your problem, but I know jQuery is very strict about JSON formatting. Some of your JSON values aren't enclosed in quotes. For example:

"status":0

I'm not at a place where I can easily confirm that in my own environment, so it might be a total red herring. But it might be worth a quick double-check.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜