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 ,本文僅供參考,請勿轉載,謝謝

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM