2011-11-25 71 views
0

我们一直在试图让JSONP工作的ASP.NET范围摔跤。我们试图检查一个文件是否存在于不同的服务器上并返回一个布尔值。该函数在jquery的ready()函数上调用,所以它应该在加载所有DOM元素之后发生。JSONP + ASP.NET - 响应不完整

我们已经使用了HTTP模块请求/响应重写链接在这里: http://www.codeproject.com/KB/webservices/ASPNET_JSONP.aspx

的AJAX调用:

function CheckFileExists() { 
    var _FileID = $('#FileID').val(); 
    var button = $('#btnViewFiles'); 
    button.val('Checking...').css('color', ''); 
    $.ajax({ 
     type: "GET",    
     url: localAdminUrl + "WebServices.asmx/CheckFileExists", 
     data: { FileID: _FileID }, 
     contentType: "application/json; charset=utf-8", 
     dataType: "jsonp", 
     success: function (data, textStatus, jqXHR) {    
      if (data.d == true) { 
       button.attr('onClick', 'ViewFiles(_FileID,false);').removeAttr('disabled').val('View documents').css('color', '#22CA00'); 
      } else { 
       button.val('No documents').css('color', '#DD3BB3').removeAttr('onClick').attr('disabled', 'disabled'); 
      } 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 
      button.val('Error occurred').css('color', '#DD3BB3').removeAttr('onClick').attr('disabled', 'disabled'); 
     }    
    }); 
} 

现在,出于某种原因,响应偶尔决定省略结束括号和分号,留下不完整的回应,JSON在哭“parsererror”。

例如:

jQuery<numbers>_<numbers>({"d":false} 

,而不是预期:

jQuery<numbers>_<numbers>({"d":false}); 

莫名其妙的事情是,它只是偶尔发生 - 一些请​​求最终完整和正确解析。究竟是怎么回事?

我试图重写使得响应写入一次,而不是三倍的HttpModule:

public override void Write(byte[] buffer, int offset, int count) 
    { 
     var b1 = Encoding.UTF8.GetBytes(_context.Request.Params["callback"] + "("); 
     var b2 = Encoding.UTF8.GetBytes(");"); 
     byte[] finalResponse = new byte[b1.Length + buffer.Length + b2.Length]; 

     b1.CopyTo(finalResponse,0); 
     buffer.CopyTo(finalResponse, b1.Length); 
     b2.CopyTo(finalResponse, b1.Length + buffer.Length); 
     _responseStream.Write(finalResponse, 0, finalResponse.Length); 
     /* Old way 
     _responseStream.Write(b1, 0, b1.Length); 
     _responseStream.Write(buffer, offset, count); 
     var b2 = Encoding.UTF8.GetBytes(");"); 
     _responseStream.Write(b2, 0, b2.Length); 
     */ 
} 

似乎并不虽然已经帮助。

+0

看起来像'_responseStream'没有被刷新/丢弃。很难肯定地说,没有看看调用'Write()'的代码' –

+0

你可以在关于'_responseStream'中加入更多代码吗? –

回答