用户登录
用户注册

分享至

js跨域调用WebService的简单实例

  • 作者: 丅1秒待續
  • 来源: 51数据库
  • 2021-08-04

步骤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://www.51sjk.com/Upload/Articles/1/0/263/263788_20210708001603534.jpg")]
  [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/antiwebquery_ajax?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的简单实例的全部内容了,希望对大家有所帮助,多多支持~

软件
前端设计
程序设计
Java相关