jQuery Ajax调用一个奇怪的问题及解决方案
今天在使用jQuery Ajax post的时候发现了一个奇怪的问题,示例代码如下,就是简单的提交两个值到后台代码,如果两个值相等就返回一个空对象,否则返回一个填充好数据的对象。
$(document).ready(function () { $('#button').click(function () { $.post('/Home/AjaxDemo', { Value1: $('#valueInput1').val(), Value2: $('#valueInput2').val() }, $.proxy(function (data) { var testInstance = data; if (testInstance) { alert("Got a instance from server."); } else { alert("Create a default client instance."); } }, this)).fail($.proxy( function (err) { if (err.status() != 0) { alert("Create instance fail!"); } }, this)); }); });
[HttpPost] public JsonResult AjaxDemo(string Value1, string Value2) { return Value1 == Value2 ? Json(null) : Json(new { Id = 1, data = "Test Data" }); }
看上去代码很简单,之前项目里的代码也是这么写的运行一切正常,在我把项目里的jQuery从1.4.4升级到1.10.2之后就出现问题了,只要后台代码返回null结果,ajax调用就会出错,直接执行fail回调里的方法。费半天劲终于在jQuery文档里找到了线索,原文如下:
http://jquery.com/upgrade-guide/1.9/#jquery-ajax-returning-a-json-result-of-an-empty-string
Prior to 1.9, an ajax call that expected a return data type of JSON or JSONP would consider a return value of an empty string to be a success case, but return a null to the success handler or promise. As of 1.9, an empty string returned for JSON data is considered to be malformed JSON (because it is); this will now throw an error. Use the error handler to catch such cases.
简短来说就是从1.9开始在解析一个空字符串json对象的时候会抛出一个错误。
看来只能自己在代码里处理了,解决方案也很简单,从后台不直接返回null,而是返回一个Json(new { }),然后在ajax回调里使用isEmptyObject方法来判断是否空对象。改进后的代码如下:
$(document).ready(function () { $('#button').click(function () { $.post('/Home/AjaxDemo', { Value1: $('#valueInput1').val(), Value2: $('#valueInput2').val() }, $.proxy(function (data) { var testInstance = data; if (!$.isEmptyObject(testInstance)) { alert("Got a instance from server."); } else { alert("Create a default client instance."); } }, this)).fail($.proxy( function (err) { if (err.status() != 0) { alert("Create instance fail!"); } }, this)); }); });
[HttpPost] public JsonResult AjaxDemo(string Value1, string Value2) { return Value1 == Value2 ? Json(new { }) : Json(new { Id = 1, data = "Test Data" }); }

浙公网安备 33010602011771号