1.
客户端代码:
$.ajax({ data: { name: 'zhangsan' }, url: apiUrl.getTwo('TestFourth'), dataType: 'jsonp', success: function (data) { alert(data); }, error: function (XMLRequest, textStatus) { console.info(XMLRequest); console.info(textStatus); alert('失败'); }});
2.使用Controller的Action返回字符串类型,从从服务端返回的总是字符串,给字符串添加了双引号,所以在Jquery的jsonp返回函数中解析失败
[HttpGet]public string TestTwo(string callback){ string json = "{'name':'张三','age':'20'}"; string result = string.Format("{0}({1})", callback, json); return result;}
返回结果:
3.手动输出结果,不待双引号解析成功
[HttpGet]public void TestThree(string callback){ string json = "{'name':'张三','age':'20'}"; string result = string.Format("{0}({1})", callback, json); //使用当前HttpResponseBase输入结果 ReqHelper.resp.Write(result); //在WebApi中需要手动输出缓存内容 ReqHelper.resp.End();}[HttpGet]public void TestFourth(string callback){ object obj = new { name = "李四", age = 25 }; string json = obj.ToJsonString(); string result = string.Format("{0}({1})", callback, json); ReqHelper.resp.Write(result); ReqHelper.resp.End();}
返回结果如: