附加到Json的jQuery AJAX返回数据"d:null"

Ste*_*hRT 7 javascript ajax jquery json web-services

嘿所有我在使用AJAX POST方法调用我的webservice时从回调中获得奇怪的回报.

Web服务正在发回JSON,如下所示:

Dim ser As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim strResponse As String = ser.Serialize(results)

Context.Response.Clear()
Context.Response.ContentType = "application/json"
Context.Response.AddHeader("content-length", strResponse.Length.ToString())
Context.Response.Write(strResponse)
HttpContext.Current.ApplicationInstance.CompleteRequest()
Run Code Online (Sandbox Code Playgroud)

上面的strResponse的值是:

"[{\"Column1\":\"0589S2F\"},{\"Column1\":\"53699FNS\"},{\"Column1\":\"C38VVFD\"},{\"Column1\":\"LFD55F\"},{\"Column1\":\"2ERfG\"},{\"Column1\":\"0079\"},{\"Column1\":\"2054\"},{\"Column1\":\"054FGW\"}]"
Run Code Online (Sandbox Code Playgroud)

由于某种原因,我的ajax返回200 OK但仍然进入ERROR逻辑,错误消息为:

ERROR: "[{\"Column1\":\"0589S2F\"},{\"Column1\":\"53699FNS\"},{\"Column1\":\"C38VVFD\"},{\"Column1\":\"LFD55F\"},{\"Column1\":\"2ERfG\"},{\"Column1\":\"0079\"},{\"Column1\":\"2054\"},{\"Column1\":\"054FGW\"}]"{"d":null}
Run Code Online (Sandbox Code Playgroud)

请注意它如何将{"d":null}附加到我的请求的末尾...那是从哪里来的,因为我没有在strResponse中发送任何类似的 东西

我的ajax请求代码:

var sqlQ = "SELECT TOP 50 LTRIM(RTRIM(REPLACE(OID, ' ', ''))) FROM vwPSDAT WHERE OID != ''";

$.ajax({
     type: 'POST',
     contentType: 'application/json; charset=utf-8',
     dataType: 'json',
     url: 'http://zzzz/Service1.asmx/theQ',
     data: JSON.stringify({ qString: [sqlQ] }),
     async: true,
     cache: false,
     success: function (data) {
        var obj = jQuery.parseJSON(data);
        console.log('done!');                  
     },
     error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log('ERROR: ' + XMLHttpRequest.responseText);
     }
});
Run Code Online (Sandbox Code Playgroud)

Ste*_*hRT 7

好吧,我似乎只需要添加Context.Response.Flush()在写入页面之前.

Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-length", strResponse.Length.ToString());
Context.Response.Flush();
Context.Response.Write(strResponse);
HttpContext.Current.ApplicationInstance.CompleteRequest();
Run Code Online (Sandbox Code Playgroud)

一旦我这样做,一切都很好.

  • 写入后应调用刷新 (2认同)