3

如何提取没有标题的响应内容(仅正文)?

$.ajax({ 
   type: "GET",
   url: "http://myRestservice.domain.com",
   success: function(data, textStatus, request){
        alert(data); //This prints the response with the header.

   },
   error: function(){
     alert('fail');

   }
  });

上面的代码打印

HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 12 Jul 2013 20:24:06 GMT
Content-Length: 232

    <?xml version="1.0" encoding="utf-8"?>
    <string xmlns="http://tempuri.org/">{"UserID":3,"RoleID":8,"ActivityID":3,"RoleIName":"E",,"Duration":10,"ValidationMsg":"Passed"}</string>

我需要提取ValidationMsg 的值。这是一个休息服务电话。

如何在没有标头信息的情况下获得响应?

4

3 回答 3

4

I think your server is delivering a content type that you aren't expecting.

Steps to resolve:

  • Open up the network tab in chrome's developer tools, watch the request occur and read what content type it is being delivered as. I bet, it is something like text/plain or text/html.
  • For JSON your server should be delivering it as application/json.
  • Your ajax request should specify dataType as 'json'. Normally $.ajax guesses appropriately; however, since your server is claiming it is text of some sort you are getting headers in your response.
于 2013-07-15T18:55:43.603 回答
2

如果您在data参数中取回标头,我怀疑您的服务器代码有问题。您提供的代码适用于我连接到返回有效 XML 的测试服务器 - data参数最终包含一个 XML 文档对象。

我建议您尝试在浏览器中打开该网址并查看它返回的内容。此外,如果 XML 是在服务器上以编程方式生成的,您可以尝试只创建一个静态 XML 文件,看看是否效果更好。

一旦服务器返回有效的 XML,您就可以从data参数中的 XML 对象中提取字符串内容,如下所示:

var stringContent = $(data).text();

然后,您可以使用以下方法从该字符串内容中解析 JSON:

var json = $.parseJSON(stringContent);

最后提取validationMessage键:

var validationMessage = json.ValidationMsg;

这是假设该字符串元素中的 JSON 是有效的 json。但是,在您给出的示例中,“RoleIName”和“Duration”之间有一个双逗号,这使其无效。

如果你不能在服务器端修复它,你可以在客户端用一个简单的字符串替换来修复它,如下所示:

stringContent = stringContent.replace(',,', ',');

一般来说,这并不是一件特别安全的事情,但是如果您不担心 json 内容中的逗号可能会被此类调用破坏,那么这应该不是问题。

综上所述,最终的成功函数应该如下所示:

success: function(data, textStatus, request){
   var stringContent = $(data).text();
   stringContent = stringContent.replace(',,', ',');
   var json = $.parseJSON(stringContent);
   var validationMessage = json.ValidationMsg;
   /* do whatever you need with the validationMessage here */
},

这是一个演示工作脚本的 codepen 链接:http: //codepen.io/anon/pen/LeDlg

于 2013-07-15T18:08:27.870 回答
0

我的想法是尝试在您的 ajax 调用中使用 contentType:

$.ajax({ 
   type: "GET",
   url: "http://myRestservice.domain.com",
   **contentType: "application/json",**
   success: function(data, textStatus, request){
        alert(data); //This prints the response with the header.

   },
   error: function(){
     alert('fail');

   }
  });

然后尝试捕获 json 对象

于 2013-07-12T22:20:37.250 回答