angularjs跨域调取webservice

1、配置

web.config

<webServices>
			<!--必须添加-->
			<protocols>
				<add name="HttpGet"/>
				<add name="HttpPost"/>
			</protocols>
		</webServices>

		<httpModules>
			<add name="JsonpHttpModule" type="MJN.Common.JsonpHttpModule" />
		</httpModules>

webservice.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using MJN.Common;

namespace MJN
{
    /// <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 getTime()
        {
            ResonseMessage result = new ResonseMessage()
            {
                state = "1",
                msg = new Random().Next(1, 10000).ToString()
            };
            return result.ToJson();
        }

    }
}

 

angularjs

services.factory('httpService', ['$resource', '$http', '$q', '$templateCache',
		function ($resource, $http, $q, $templateCache) {
		    return {
		        setting: function (url, data) {
		            var deferred = $q.defer();
		            method = (url.indexOf('http') > -1) ? 'JSONP' : 'POST';
		            $http({
		                method: method,
		                url: url,
		                cache: $templateCache,
		                data: data
		                //headers: { 'Content-Type': 'application/json;charset=UTF-8' }
		                //headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
		            }).success(function (data, status, headers, config) {
		                deferred.resolve(data, status, headers, config);
		            }).error(function (data, status, headers, config) {
		                deferred.reject("network error");
		            });
		            return deferred.promise;
		        }
		    };
		} ]);

  

调用:

httpService.setting('http://10.20.26.19/mjn/WebService1.asmx/getTime?callback=JSON_CALLBACK&format=jsonp&t=' + new Date().getTime()).then(function (data, status, headers, config) {
            console.log(data);
        }, function (reason) {
            console.log(reason);
        });

  

 

posted @ 2016-07-15 16:42  徐大腿  阅读(3015)  评论(1编辑  收藏  举报