js跨域调用WebService的简单实例

步骤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/json;charset=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> 

补充内容:

//跨域传值
	function RequestByJsonPMuti(userid,username)
	{
        //使用json格式
        var dataStr ={
        "userid" :userid,
        "username":username       	
        }; 
        $.ajax({
          type: "get",
          //url: "http://xxx/xxx.asmx/AntiWebQuery_Ajax?jsoncallback?",
          //WebServices地址(getUserNameid4=方法名称,?jsoncallback=?--必须包含,192.168.0.100為遠程的server,不是本機)
          url:"http://192.168.0.100/WTled.link/ReelUpdown.asmx/getUserNameid4?jsoncallback?",
          dataType: "jsonp",
          jsonp: 'jsoncallback',
          data: dataStr,
          //contentType: "application/json; charset=utf-8",
          success: function (result) {
            //返回结果
            alert(result.userid+"<>"+result.username);
          }
        });		
	}
	// 后台webservices 代码
	 [WebMethod(Description = "测试4")]
        public void getUserNameid4(string userid, string username)
        {
            HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";
            string jsonCallBackFunName = string.Empty;
            Hashtable list = new Hashtable();
            list.Add("userid",userid);
            list.Add("username",username);
            JavaScriptSerializer ser = new JavaScriptSerializer();
            String jsonStr = ser.Serialize(list);//{"userid":"211","username":"dsd"}
            jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();
            HttpContext.Current.Response.Write(jsonCallBackFunName +"("+ jsonStr+")");
            HttpContext.Current.Response.End();
           
         //其中将泛型集合使用了Json库(第三方序列json数据的dll)转变成json数据字符串,必须引用第三方库及引用命名空间using Newtonsoft.Json;
         //string result = jsoncallback + "(" + JsonConvert.SerializeObject(responseResult, Formatting.Indented) + ")";
         //HttpContext.Current.Response.Write(result);
         //HttpContext.Current.Response.End();        
        }
      
        //JS调用:
        RequestByJsonPMuti("00119988","Wang wu");

             //WebService项目配置文件
		<system.web>
		    <!--提供Web服务访问方式-->
		    <webServices>
		      <protocols>
		        <add name="HttpSoap"/>
		        <add name="HttpPost"/>
		        <add name="HttpGet"/>
		        <add name="Documentation"/>
		      </protocols>
		    </webServices>
		</system.web>
		
	    //由于使用jquery.getJson的方式调用Web服务后,传递中文时会造成中文乱码问题:		
		//所以在配置文件中应配置如下内容:		
		<system.web>
		    <!-- 设定传参乱码问题 -->
		    <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8"/>
		</system.web>	
	

不能跨域的,只能本地调用:

//本地调用,不能跨域
	function RequestByGet(data)
	{
		var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		var URL="http://192.168.0.1:2004/jstest.asmx";
		xmlhttp.Open("GET",URL, false);
		xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8");
		xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/SayHelloTo?Name=Zach");
		xmlhttp.Send(data);
		var result = xmlhttp.status;
		
		alert("result:"+xmlhttp.responseText);
		//OK
		if(result==200) {
		document.write(xmlhttp.responseText);
		}
		xmlhttp = null;
	}		
	//test function with post method
	//本地调用,不能跨域
	function RequestByPost(value)
	{
		var data;
		data = '<?xml version="1.0" encoding="utf-8"?>';
		data = data + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
		data = data + '<soap:Body>';
		data = data + '<SayHelloTo xmlns="http://tempuri.org/">';
		data = data + '<Name>'+value+'</Name>';
		data = data + '</SayHelloTo>';
		data = data + '</soap:Body>';
		data = data + '</soap:Envelope>';
		
		var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		var URL="http://192.168.0.1:2004/jstest.asmx";
		xmlhttp.Open("POST",URL, false);
		xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8");
		xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/SayHelloTo");
		xmlhttp.Send(data);
		alert(xmlhttp.responseText);
		document.write( xmlhttp.responseText);
	} 

JS调用:
  RequestByGet(null);
  RequestByPost('sjksd');





  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值