代码之家  ›  专栏  ›  技术社区  ›  Clayton

使用jqueryajax检索纯文本并转换为JSON

  •  2
  • Clayton  · 技术社区  · 14 年前

    更新:

    $.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);
    });
    

    我有一个jetty服务器,它将json数据生成为纯文本-标题如下:

    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)
    

    {
     "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"},
        {
         "citystate":"Seaton, AR"}]
     }}
    

    我想使用jquery ajax调用检索此数据,如下所示:

    $.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");
      }
    });
    

    但是,我得到的结果总是空的。我做错什么了?

    2 回复  |  直到 14 年前
        1
  •  -2
  •   dev-null-dweller    14 年前

    Content-type 应用程序/json 文本/javascript )你应该期待纯文本 dataType: 'text'

    function(data){
        eval('var data = ' + data + ';');
        // Rest of your code
    }
    
        2
  •  -2
  •   mikemanne    14 年前

    不确定这是否是问题的根本原因,但我知道jQuery对JSON格式非常严格。有些JSON值没有用引号括起来。例如:

    "status":0