html5 app开发实例 Ajax跨域访问C# webservices服务

通过几天的研究效果,如果在vs2010工具上通过webservice还是比较简单的,毕竟是一个项目。

如果您想通过HTML5 做出来的移动APP去访问c#做出来的webservice,那么就没那么简单了,应为不是一个项目,而且部署到外网服务器上以后数据跨域访问。

自己琢磨了两三天,还搞了一台腾讯云服务器来测试,测试没问题,具体操作,直接看代码。

HBuilder 前端html代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title></title>
    <script src="js/mui.min.js"></script>
    <link href="css/mui.min.css" rel="stylesheet"/>
    <link rel="stylesheet" type="text/css" href="css/index.css"/>
    <script type="text/javascript" src="js/jquery-2.1.0.js" ></script>
    <script type="text/javascript" src="js/index.js" ></script>
    <script type="text/javascript" charset="utf-8">
          mui.init();
    </script>
</head>
<body>
    <header class="mui-bar mui-bar-nav">
        <h1 class="mui-title">测试 Ajax 调用云端WebServices</h1>
    </header>
    <div class="mui-content">
        <div id="">
            <button type="button" class="mui-btn mui-btn-blue mui-btn-outlined" onclick="dbOnclick1()">Ajax WebServices按钮</button>
        </div>
    
        <div id="">
            <div class="mui-input-row">
                <label>name</label>
                <input type="text" id="txt-name" placeholder="请输入您的姓名">
            </div>
            
            <button type="button" class="mui-btn mui-btn-blue mui-btn-outlined" onclick="dbOnclick2()">带参数Ajax WebServices按钮</button>
        </div>
        
        <div id="divRes">
            
        </div>
        <p><br>按钮1,直接获取webservices接口的返回值</p>
        <p>按钮2,传输用户输入的内容后,获取webservices接口的返回值</p>
        <button type="button" class="mui-btn mui-btn-blue mui-btn-block" onclick="dbOnclick3()">按钮</button>
    </div>
    <nav class="mui-bar mui-bar-tab">
        <a class="mui-tab-item mui-active">
            <span class="mui-icon mui-icon-home"></span>
            <span class="mui-tab-label">首页</span>
        </a>
        <a class="mui-tab-item">
            <span class="mui-icon mui-icon-phone"></span>
            <span class="mui-tab-label">电话</span>
        </a>
        <a class="mui-tab-item">
            <span class="mui-icon mui-icon-email"></span>
            <span class="mui-tab-label">邮件</span>
        </a>
        <a class="mui-tab-item">
            <span class="mui-icon mui-icon-gear"></span>
            <span class="mui-tab-label">设置</span>
        </a>
    </nav>
    

</body>
</html>

HBuilder 前端js代码

/// <reference path="jquery-2.1.0.js" />
//function ajaxOn() {
var urlStr1="http://118.89.27.204:8080/WebService1.asmx/HelloWorld";
var urlStr2="http://118.89.27.204:8080/WebService1.asmx/HelloWorldName";
//  
//

function dbOnclick1(){
   
      jQuery.support.cors = true; //IE10以下
        $.ajax({
            type: "post",
            url: urlStr1,
            dataType: 'xml',
            //data: { inputStr: 'everyone' },
            success: function (data) {
                   document.getElementById("divRes").innerText=data.lastChild.textContent;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest);
                alert('error:' + errorThrown);
            }
        });
}
function dbOnclick2(){
   
      jQuery.support.cors = true; //IE10以下
        $.ajax({
            type: "post",
            url: urlStr2,
            dataType: 'xml',
            data: { name: $("#txt-name").val() },
            success: function (data) {
                document.getElementById("divRes").innerText=data.lastChild.textContent;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest);
                alert('error:' + errorThrown);
            }
        });
}

C# webservices代码

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

namespace WebApplication2
{
    /// <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
    {
        [WebMethod]
        public string HelloWorld()
        {
            //注意这句,跨域的关键
            Context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            return "Hello World \r\n 这是一个不带参数的webservices方法";
        }
        [WebMethod]
        public string HelloWorldName(string name)
        {
            //注意这句,跨域的关键
            Context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            return name + "  Hello World \r\n 这是一个带参数的webservices方法";
        }
    }
}

如果还是不能获取到webservices服务的数据可以尝试修改配置文件“Web.config”

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

<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off"/>
    <webServices>
      <protocols>
        <add name="HttpSoap"/>
        <add name="HttpPost"/>
        <add name="HttpGet"/>
        <add name="Documentation"/>
      </protocols>
    </webServices>
  </system.web>

</configuration>

手机测试图片

          

其他条码知识 请访问:http://www.ybtiaoma.com ,本文仅供参考,请勿转载,谢谢

  

posted @ 2017-05-27 16:58  渴死的鱼0521  阅读(2260)  评论(0编辑  收藏  举报