首页 > Web开发 > 详细

jquery ajax CORS 跨域访问 WebService

时间:2015-07-23 21:55:50      阅读:425      评论:0      收藏:0      [点我收藏+]

JS代码:

var word = document.getElementById("word").value;
$.ajax({
    type: "POST",
    contentType: "application/x-www-form-urlencoded",
    url: "http://localhost:12805/WebService.asmx/HelloWorld",
    data: 'data=' + word,
    dataType: 'text',
    success: function(result) {
        alert("success: " + result);
    },
    error: function(result, status) {
        alert("error: " + status);
    }
});

C# WebService代码:

[WebService(Namespace = "weburl")]
[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]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public void HelloWorld(string data)
    {
        this.Context.Response.AddHeader("Access-Control-Allow-Origin", "*"); // CORS 跨域访问
        this.Context.Response.Write(data); // 返回字符串格式
    }
}

WebService 默认 return 返回 XML 格式,但是使用上述方式是以字符串形式返回。


版权声明:本文为博主原创文章,未经博主允许不得转载。

jquery ajax CORS 跨域访问 WebService

原文:http://blog.csdn.net/colorwaterer/article/details/47027253

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!