javascript的跨域調用

【服務端】ajax

 

[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();
        }
    }

【客戶端】json

1、完整寫法:app

$.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);
        }
      });

2、簡化寫法:post

$.getJSON("http://localhost:3997/Service1.asmx/Hello?callback=?",{"js":"董瑋"},
      function(data)
      {
      alert(data);
      },"post");
相關文章
相關標籤/搜索