我們一直在試圖讓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);
*/
}
似乎並不雖然已經幫助。
看起來像'_responseStream'沒有被刷新/丟棄。很難肯定地說,沒有看看調用'Write()'的代碼' –
你可以在關於'_responseStream'中加入更多代碼嗎? –