1. 程式人生 > >js呼叫Webservice介面案例

js呼叫Webservice介面案例

第一步:新建Webservice介面

主檔案方法

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;

namespace TestWebApplication
{
/// <summary>
/// WebService1 的摘要說明
/// </summary>
[WebService(Namespace = "http://10.12.1.90:5555/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService

]//(AJAX呼叫必須放開註釋,net framwork 4.0版本及更高版本)
public class WebService1 : System.Web.Services.WebService
{

[WebMethod]
public string HelloWorld()
{
var ss = Context.Request.QueryString["fname"];
return "Hello World"+ ss;
}

[WebMethod]
public string HelloWorld1(string ww)
{

Context.Response.Charset = "GB2312"; //設定字符集型別
Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Context.Response.Write("success");
Context.Response.End();

}
}

 

配置檔案Web.config

<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<!--
有關 web.config 更改的說明,請參見 http://go.microsoft.com/fwlink/?LinkId=235367。

可在 <httpRuntime> 標記上設定以下特性。
<system.Web>
<httpRuntime targetFramework="4.5" />
</system.Web>
-->
<system.web>
<!--請求設定-->
<httpRuntime maxRequestLength="204800" executionTimeout="3600

"/>
<compilation debug="true" targetFramework="4.5"/>
<!--設定允許http,post,get方式請求-->
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
</webServices>
<!--<compilation debug="true" targetFramework="4.0" />-->
<!--
通過 <authentication> 節,可配置
ASP.NET 用於識別進入使用者的
安全身份驗證模式。
-->
<authentication mode="Windows"/>
<!--
通過 <customErrors> 節,可以配置
在執行請求的過程中出現未處理的錯誤時要執行
的操作。具體而言,
開發人員通過該節可配置要顯示的 html 錯誤頁,
以代替錯誤堆疊跟蹤。

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>

 

第二步:前臺js通過ajax呼叫Webservice介面(本檔案是一個html檔案,包含一個按鈕,點選按鈕,js通過ajax呼叫Webservice介面)

<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var XMLHttpReq;
function createXMLHttpRequest() {
try {
XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); //IE高版本建立XMLHTTP
}
catch (E) {
try {
XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); //IE低版本建立XMLHTTP
}
catch (E) {
XMLHttpReq = new XMLHttpRequest(); //相容非IE瀏覽器,直接建立XMLHTTP物件
}
}
}

function sendAjaxRequest(url) {
//alert(url);
var json;
createXMLHttpRequest();
XMLHttpReq.open("post", url, false);
XMLHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//請求標頭檔案設定編碼
XMLHttpReq.onreadystatechange = function () {
if (XMLHttpReq.readyState == 4) {
if (XMLHttpReq.status == 200) {
document.getElementById("myDiv").innerHTMLXMLHttpReq.responseText

json = eval("(" + XMLHttpReq.responseText + ")");

}
}
}
XMLHttpReq.send("ww=123");//引數

return json;
}
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("post","http://localhost:58081/WebService1.asmx/HelloWorld1",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("ww=123");

}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">請求資料</button>
<div id="myDiv"></div>
<body>
<input id="Button1" type="button" onclick="sendAjaxRequest('http://localhost:58081/WebService1.asmx/HelloWorld1')" value="button" />

</body>
</body>
</html>