js怎么调用webserver

JavaScript021

js怎么调用webserver,第1张

步骤1.   在web.config中的system.web节点里加入

<!--此节点可允许脚本跨域调用webservice-->

  <webServices>

   <protocols>

    <add name="HttpPost"/>

    <add name="HttpGet"/>

   </protocols>

  </webServices>

  <!--此节点可允许脚本跨域调用webservice-->

步骤2. webservice代码

using System

using System.Collections.Generic

using System.Linq

using System.Web

using System.Web.Services

using System.Web.Mvc

namespace WebService

{

  /// <summary>

  /// WebService1 的摘要说明

  /// </summary>

  [WebService(Namespace = "http://tempuri.org/")]

  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

  [System.ComponentModel.ToolboxItem(false)]

  // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。

  [System.Web.Script.Services.ScriptService]

  public class WebService1 : System.Web.Services.WebService

  {

    [ValidateInput(false)]

    [WebMethod(Description = "测试")]

    public void getDBTableInfos(string EnterpriseCode)

    {

      HttpContext.Current.Response.ContentType = "application/jsoncharset=utf-8"

      string jsonCallBackFunName = string.Empty

      jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString()

      HttpContext.Current.Response.Write(jsonCallBackFunName + "({ \"Result\": \"" + EnterpriseCode + "\" })")

    } 

  }

步骤3. html页面部分

<!DOCTYPE html>

<html>

<head>

  <title>Index</title>

  <script src="http://www.cnblogs.com/Scripts/jquery-1.5.1.js" type="text/javascript"></script>

  <script type="text/javascript">

    $(function () {

      $("#btnSubmit").click(function () {

        var EnterpriseCode = "39"       

        var dataStr = "EnterpriseCode=" + EnterpriseCode

        $.ajax({

          type: "get",

          url: "http://xxx/xxx.asmx/getDBTableInfos?jsoncallback?",

          dataType: "jsonp",

          jsonp: 'jsoncallback',

          data: dataStr,

          success: function (result) {

            //返回结果

            alert(result.Result)

          }

        })

      })

    })

  </script>

</head>

<body>

  <div>

    <input id="btnSubmit" type="button" value="查询" />

  </div>

</body>

</html>

 要想实现JS调用WebService,可以按如下步骤实现(经过测试):

第一步:创建一个WebService

在此处我就创建了一个默认的web服务,并不做什么修改,把主要集力放在怎么实现JS调Web服务上面。

using System

using System.Collections.Generic

using System.Web

using System.Web.Services

/// <summary>

///WebService 的摘要说明

/// </summary>

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class WebService : System.Web.Services.WebService

{

public WebService()

{

//如果使用设计的组件,请取消注释以下行

//InitializeComponent()

}

[WebMethod]

public string HelloWorld()

{

return "Hellow World"

}

}第二步:创建一个页面,实现JS调用Web服务

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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></title>

<script type="text/javascript">

function RequestWebService() {

//这是我们在第一步中创建的Web服务的地址

var URL = "http://localhost/YBWS/WebService.asmx"

//在这处我们拼接

var data

data = '<?xml version="1.0" encoding="utf-8"?>'

data = data + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">'

data = data + '<soap12:Body>'

data = data + '<HelloWorld xmlns="http://tempuri.org/" />'

data = data + '</soap12:Body>'

data = data + '</soap12:Envelope>'

//创建异步对象

var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")

xmlhttp.Open("POST", URL, false)

xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml")

xmlhttp.Send(data)

document.getElementById("data").innerHTML = xmlhttp.responseText

}

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

<input id="One" type="button" value="JsCallWebService" onclick="RequestWebService()" />

</div>

<div id="data">

</div>

</form>

</body>

</html>

直接使用xmlhttp将请求发送至webservice接口,并返回结果

参考说明:

在IE中XmlHttp被实现为ActiveX对象,通常使用var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")也可以使用var xmlhttp = createobject("MiCROSOFT.XMLHTTP") 来创建一个对象,然后使用该对象的open方法来发出一个Http请求。

xmlhttp.open("GET", fragment_url)

这时候浏览器已经发出了Http请求,我们需要注册一个匿名函数给XmlHttp对象的onreadystatechange方法,这样当请求返回时,xmlhttp就会自动调用我们注册的这个函数,下边是一个实际的例子。

xmlhttp.onreadystatechange = function()

{

if (xmlhttp.readyState == 4 &&xmlhttp.status == 200)

{

element.innerHTML = xmlhttp.responseText

}

}

因为我们不需要再发送任何信息,所以用下边的语句结束

xmlhttp.send(null)

我们将上边的过程封装为一个函数,下边是这个函数的完整代码:

function loadFragmentInToElement(fragment_url, element_id)

{

var element = document.getElementById(element_id)

varxmlhttp = new ActiveXObject("Msxml2.XMLHTTP")

xmlhttp.open("GET", fragment_url)

xmlhttp.onreadystatechange = function()

{

if (xmlhttp.readyState == 4 &&xmlhttp.status == 200)

{

element.innerHTML = xmlhttp.responseText

}

}

xmlhttp.send(null)

PHPMORE VOL5 24/26

}