ajax跨域请求调用webservice接口

最近突然想学习webservice,一直不知道如何跨域调用调用。如果都在同一个项目,相信大家都知道了?特此整理一下关键点,权当学习。

1.WebService 接口编写。这里不在赘述。

步骤:新建web项目=》添加web service=》编写方法接口=》然后发布。

关键如何让外部Ajax 调用。

首先,配置WebService 项目配置文件(web.config)红色部分必须配置,这样第三方才能调用接口方法(经测试通过,直接粘贴就ok),不懂可以百度。

 


    
      
        
          
          
          
          
        
      
        
    
  


    
      
        
        
        
      
    
  
 
        
          
          
          
          
        
      
        
    
  


    
      
        
        
        
      
    
  


其次,这里贴出WebService 中代码部分,这里我自定义一个返回一个Person集合GetPersonList(),可供Ajax调用。

 

(1)发布时需要配置[WebService(Namespace = "http://192.168.1.90:5555/")]//这里定义你发布以后的域名地址。当然本地测试使用localhost就可以。

(2)要放开[System.Web.Script.Services.ScriptService] 的注释。

以上两步做到写接口发布WebService,访问http://192.168.1.90:5555/XXX.asmx 地址。

 

 

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

namespace WebAPI 
{
    /// 
    /// Summary description for WebService1
    /// 
    //[WebService(Namespace = "http://localhost:9999/")]//本地测试可以使用localhost。
    [WebService(Namespace = "http://192.168.1.90:5555/")]//这里定义你发布以后的域名地址。
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]//(AJAX调用必须放开注释)
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod(Description = "你好世界")]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public string HelloName(string name)
        {
            return "Hello," + name;
        }

        [WebMethod]
        public List GetPersonList()
        {
            List lst = new List();
            lst.Add(new Person { id = 1, name = "小明", age = 34 });
            lst.Add(new Person { id = 1, name = "小明", age = 34 });
            lst.Add(new Person { id = 1, name = "小明", age = 34 });
            lst.Add(new Person { id = 1, name = "小明", age = 34 });

            return lst;
        }
    }

    public class Person
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
    }
}


3.第三方Ajax调用。我直接返回的是xml格式,当然你也可以在接口中定义返回json(此处取出xml文本并输出在页面)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(web,service,ajax,WebService)