在2.0下运行的webservice 怎样才能输出json?
前端调用代码如下:
function exData(url, params, onS, onF) {
Ext.lib.Ajax.defaultPostHeader = 'application/json';
var format;
if (params != null)
format = {
headers:{'Content-Type':'application/json;utf-8'},
url: url,
method: 'POST',
params: Ext.util.JSON.encode(params),
success: onS,
failure: onF
};
else
format = {
url: url,
method: 'POST',
success: onS,
failure: onF
};
Ext.Ajax.request(format);
}
var hello = function() {
var onS = function(r, o) {
alert(r.responseText);
};
var onF = function(r, o) {
alert(r.responseText);
};
var url = 'wsCategory.asmx/hello';
exData(url, null, onS, onF);
};
hello();
=======================================
webservice方法如下:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string hello()
{
return "hello";
}
在此方法的类上面已经标有[ScriptService]
[解决办法]
ding
[解决办法]
发现.net自带的ajax.net使用webservice输出的是json,其中关键的就是在请求时:Content-Type:application/json;utf-8
所以我们只要在POST时加上一个Content-Type:application/json;utf-8就可以了
$.ajax({
type: "POST",
contentType:"application/json;utf-8",
url: "/Server/PicLib.asmx/HelloWorld",
success: function(msg){
var json = eval('(' + msg + ')');
alert(json.d);}
});
var json = eval('(' + msg + ')');
(这个是把返回的字符值转换成json对象,这样子才能够正常的操作json,这里可以用try来捕捉一下错误,因为如果返回的字符串不是标准的json的话就会出错。)
上面的js要成功运行需要对.net做一下设置让“WebService输出JSON”
修改WebService,导入一个属性
<System.Web.Script.Services.ScriptService()> <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class WebService1
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function HelloWorld(ByVal str As String, ByVal name As String) As String
Return str & name
End Function
End Class
在webconfig中添加:
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpHandlers>
注意:这个是关键,这样子才能使请求asmx文件时让它输出json格式,刚刚开始时测试了很久都不行。
[解决办法]
更改:web service输出端代码
部分代码如下:
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
{
//省略掉数据打开部分代码
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("{totalCount: 100, items: [");
foreach (DataRow dr in dt.Rows)
{
sb.Append("{");
sb.AppendFormat("TestName:'{0}',TestValue:'{1}'", dr[0], dr[1]);
sb.Append("},");
}
sb.Remove(sb.length,1);
sb.Append("]}");
//输出拼成的json
context.Response.Write(sb);