【问题标题】:Why is a linefeed char added to the http response?为什么在 http 响应中添加换行符?
【发布时间】:2011-11-22 23:26:17
【问题描述】:

我做这个 ajax 请求:

 var response = $.ajax({
    url: 'product/add', 
    data: $("#formAddNewRow").serialize(),
    type: "POST",
    success: function() {
    var id = response.responseText;     
                        }            
                      });  

'product/add' 是一个 symfony 动作,它可以做一些事情。操作的视图是返回的内容,出于测试目的,该文件如下所示:

<?php

 echo "test";

?>

当我在success 之后查看response.responseText 时,我得到"test\n"。我本来希望只有"test"

这是响应标头的样子:

Date    Thu, 22 Sep 2011 15:17:45 GMT
Server  Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By    PHP/5.3.5
Expires Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control   no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma  no-cache
Content-Length  5
Keep-Alive  timeout=5, max=99
Connection  Keep-Alive
Content-Type    text/html; charset=utf-8

我在其他地方向url: 'product/update' 发出ajax 请求,它的代码完全相同(&lt;?php echo "test"; ?&gt;)。但在这种情况下response.responseText等于"test",这是我所期望的——没有添加\n。 在这种情况下,响应标头如下所示:

Date    Thu, 22 Sep 2011 15:27:20 GMT
Server  Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By    PHP/5.3.5
Expires Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control   no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma  no-cache
Content-Length  4
Keep-Alive  timeout=5, max=99
Connection  Keep-Alive
Content-Type    text/html; charset=utf-8 

我一点也不知道,为什么response.responseText 在这两种情况下都不一样。

为什么要在response.responseText 中添加换行符?

【问题讨论】:

    标签: ajax string http newline httpresponse


    【解决方案1】:

    我猜想在最后一个换行符之后有一个换行符?>

    除非我实际上将 PHP 放在 HTML 页面中,否则我总是省略最后一个?>。这不是必需的,而且往往会导致这样的问题。

    【讨论】:

      【解决方案2】:

      因为it's part of the HTTP protocol?

         Response      = Status-Line               ; Section 6.1
                         *(( general-header        ; Section 4.5
                          | response-header        ; Section 6.2
                          | entity-header ) CRLF)  ; Section 7.1
                         CRLF
                         [ message-body ]          ; Section 7.2
      

      【讨论】:

      • 好吧,我猜responseText 指的是消息体,不是吗?我在那里看不到换行符。
      • @Gert S,是的,消息正文之后似乎不应该有 CRLF。如果有的话,您可能应该从responseText 中修剪任何前导/尾随空格。
      猜你喜欢
      • 2017-04-17
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 2022-01-20
      • 2014-12-24
      • 1970-01-01
      相关资源
      最近更新 更多