首页 > 编程语言 > 详细

javascript的跨域调用

时间:2015-02-11 20:14:37      阅读:261      评论:0      收藏:0      [点我收藏+]

【服务端】

 

[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");

javascript的跨域调用

原文:http://www.cnblogs.com/ServiceboyNew/p/4286719.html

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