(环境:vs2008+jquery1.2.3)
发现.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>