ajax跨域请求调用webservice接口

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

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

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

关键如何让外部Ajax 调用。

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

 

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


    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
        <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration> <webServices>
        <protocols>
          <add name="HttpSoap"/>
          <add name="HttpPost"/>
          <add name="HttpGet"/>
          <add name="Documentation"/>
        </protocols>
      </webServices>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
  <system.webServer>


    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
        <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>


其次,这里贴出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>
    /// Summary description for WebService1
    /// </summary>
    //[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<Person> GetPersonList()
        {
            List<Person> lst = new List<Person>();
            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文本并输出在页面)

 

 

<script type="text/javascript">
    $(function () {
        $.ajax({
            type: "POST", //访问WebService使用Post方式请求
            //contentType: "application/json;charset=utf-8", //WebService 会返回Json类型
            contentType: "application/xml;charset=utf-8", //WebService 会返回xml类型
            url: "http://192.168.1.90:5555/WebService1.asmx/GetPersonList", //调用WebService
            data: "{}", //Email参数
            dataType: 'xml',
            beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/xml; charset=utf-8"); },
            error: function (x, e) { },
            success: function (response) { //回调函数,result,返回值
               
                //var json = eval('(' + response.d + ')');

                var json = $(response).text();
                document.write(json);
                //                    var userid = json.Person.id;
                //                    if (userid > 0) {
                //                        $("#username").html(json.Person.name);
                //                        $("#messagenum").html(json.Person.message);

                //                    }

            }
        });
    });
   </script>

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
要使用 AJAX 调用 Java WebService 接口,可以按照以下步骤操作: 1. 创建一个 Java WebService,例如使用 JAX-WS 标准,可以使用 JavaEE 环境或者 Apache CXF 等开源框架。 2. 在 WebService 中定义接口方法,例如: ``` @WebService public interface HelloWorld { @WebMethod String sayHello(String name); } ``` 3. 实现接口方法,例如: ``` @WebService(endpointInterface = "com.example.HelloWorld") public class HelloWorldImpl implements HelloWorld { @Override public String sayHello(String name) { return "Hello " + name + "!"; } } ``` 4. 部署 WebService 到服务器上,例如使用 Tomcat 等 Servlet 容器。 5. 在客户端页面中使用 AJAX 调用 WebService 接口,例如: ``` $.ajax({ type: "POST", url: "http://localhost:8080/HelloWorld", data: JSON.stringify({ name: "World" }), contentType: "application/json", dataType: "json", success: function (response) { alert(response); }, error: function (xhr, status, error) { alert("Error: " + error); } }); ``` 其中,url 参数为 WebService 的访问地址,data 参数为传递给接口方法的参数,contentType 参数为请求数据的 MIME 类型,dataType 参数为响应数据的 MIME 类型。在 success 回调函数中可以处理接口方法的返回值,而在 error 回调函数中可以处理错误信息。 注意,由于 AJAX 调用涉及跨域问题,需要在服务器端设置 CORS(跨域资源共享)或者使用 JSONP(JSON with Padding)等方式解决。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值