国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

用Jquery訪問WebService并返回Json的代碼第1/3頁

2024-07-10 13:21:59
字體:
供稿:網(wǎng)友
在我們的應(yīng)用中一般會是這樣的,使用了jquery作為客戶端框架,ajax請求也通常返回html或者json。html這里就不討論了。返回json一般都是搞一個handler.ashx來處理請求,拼湊字符串來返回json。從而放棄了ws,因為ws返回的是xml,使用起來不方便。
所以我覺著比較完美的解決方法是讓ws返回json而且不用asp.net ajax的客戶端框是比較理想的解決方法。
通過觀測發(fā)現(xiàn)asp.net ajax的客戶端框架請求webservice的時候返回的是json,為什么webservice沒有返回xml而返回了json呢?抓包分析到,關(guān)鍵在request的headers中 “Content-Type: application/json;utf-8” ,因此webservice就使用了json的序列化,應(yīng)該是“System.Web.Script.Serialization.JavaScriptSerializer”這個類完成的工作,通過web.config的配置,把*.asmx交給了System.Web.Extensions.Dll。也就是這里還是用了asp.net ajax,不過是用的服務(wù)端部分,我這里直接用的asp.net 3.5
以上都是在啰嗦,具體的方法很簡單,看例子
ws1.asmx 

復(fù)制代碼 代碼如下:


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace test2
{
/// <summary>
/// Summary description for WS1
/// </summary>
[WebService(Namespace = "http://one")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]

[System.Web.Script.Services.ScriptService]
public class WS1 : System.Web.Services.WebService
{

[WebMethod]
public string HelloWorld()
{
return "Hello World";
}

[WebMethod]
public TestUser CreateUser(string name,int age)
{
return new TestUser { Name = name, Age = age };
}
}

public class TestUser
{
public string Name { get; set; }
public int Age { get; set; }
}
}



test.html

復(fù)制代碼 代碼如下:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="jquery-1.2.2.js" type="text/javascript"></script>
</head>
<body>

<input type="button" value="請求HelloWorld" />
<input type="button" value="請求CreateUser" />
<script type="text/javascript">


function requestHelloWorld(){
WebService('ws1.asmx/HelloWorld',function(obj){alert(obj);});
}

function requestCreateUser(){
WebService('ws1.asmx/CreateUser',function(obj){alert(obj.Name);},'{name:"林子",age:25}');
}


function WebService(url,callback,pars){
$.ajax({
data:pars,
url: url,
type: "POST",
contentType: "application/json;utf-8",
dataType:'json',
cache: false,
success: function(json){
callback(json.d);
},
error:function(xml,status){
if(status=='error'){
try{
var json = eval('(' + xml.responseText + ')');
alert(json.Message+'/n'+json.StackTrace);
}catch(e){}
}else{
alert(status);
}
},
beforeSend:function(xml){
if(!pars) xml.setRequestHeader("Content-Type", "application/json;utf-8")
}
});
}
</script>
</body>
</html>


web.config為vs2008在.net 3.5狀態(tài)下創(chuàng)建的默認(rèn)的 也有很重要的作用 這里貼出來

復(fù)制代碼 代碼如下:


<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
<section type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="None"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<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"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption value="v3.5"/>
<providerOption value="false"/>
</compiler>
</compilers>
</system.codedom>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove/>
<add preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove/>
<remove/>
<remove/>
<remove/>
<add verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>



用javascript直接訪問asp.net的webservice,方法類似,自己構(gòu)建ajax請求而已,注意的就是設(shè)置header,剩下的asp.net 3.0以上版本會自動序列化為json
代碼下載
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 博爱县| 邻水| 托克托县| 镇沅| 石楼县| 辽宁省| 尼玛县| 尉犁县| 安吉县| 安陆市| 莱州市| 土默特左旗| 南川市| 察隅县| 达孜县| 南丹县| 澄迈县| 邵武市| 井陉县| 尉犁县| 兰溪市| 莆田市| 台南市| 樟树市| 亚东县| 宁安市| 佛冈县| 汝城县| 平顺县| 兰溪市| 广水市| 美姑县| 新建县| 化德县| 萨嘎县| 游戏| 新津县| 扶余县| 鲁山县| 乳源| 新邵县|