javascript的跨域调用

【服务端】

 

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.None)]
    [ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public void HelloWorld(string jsonStudent)
        {
            HttpResponse resp = Context.Response;
            string callBack = Context.Request["callback"].ToString();
            resp.Clear();
            resp.ContentEncoding = new UTF8Encoding(false);
            resp.ContentType = "application/json";
            resp.Charset = "utf-8";
            Student stu = JsonSerializer<Student>.Deserialize(jsonStudent);
            resp.Write(callBack+"("+JsonSerializer<Student>.Serialize(stu)+")");
            resp.End();
        }

        [WebMethod]
        public void Hello(string js)
        {
            HttpResponse resp = Context.Response;
            resp.Clear();
            resp.Charset = "utf-8";
            string callBack = Context.Request["callback"].ToString();
            resp.ContentEncoding = new UTF8Encoding(false);
            resp.ContentType = "application/json";
            string callBackFun = callBack + "('"+ js +"')";
            resp.Write(callBackFun);
            resp.End();
        }
    }

【客户端】

一、完整写法:

$.ajax(
      {
        url:"http://localhost:3997/Service1.asmx/HelloWorld",
        data:"jsonStudent={\"id\":\"1\",\"name\":\"董玮\"}",   //最好按照标准写法
        contentType:"application/json",
        type:"post",
        dataType:"jsonp",
        success:function(data)
        {
         alert(data.id+"<===>"+data.name);
        }
      });

二、简化写法:

$.getJSON("http://localhost:3997/Service1.asmx/Hello?callback=?",{"js":"董玮"},
      function(data)
      {
      alert(data);
      },"post");

转载于:https://www.cnblogs.com/ServiceboyNew/p/4286719.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值