关于ajax 跨域调用接口

方法一:

$.ajax({ 3 type : "get", 4 async : false, 5 url :xhrurl, 6 cache : false, 7 dataType : "jsonp",//这里必须要写成jsonp 8 jsonp: "callbackparam", 9 jsonpCallback:"jsonpCallback1", 10 success : function(json){ 11 alert(json[0].name); 12 }, 13 error:function(e){ 14 alert("error"); 15 } 16 });

  后台返回数据时,要修改返回格式

 String callbackFunName = context.Request["callbackparam"];
 context.Response.Write(callbackFunName + "([ { \"name\":\"John\"}])");//前面必须加上参数才可

参考:http://www.cnblogs.com/mahatmasmile/archive/2013/03/29/2989505.html

方法二:
ajax普通写法 后台使用httpwebRequest,新建一个ashx文件,ajax访问即可

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpWebRequest request = null;
HttpWebResponse response = null;
string userid=context.Request["userid"].ToString();
string pageindex=context.Request["pageindex"].ToString();
string pagesize=context.Request["pagesize"].ToString();
CookieContainer cc = new CookieContainer();
request = (HttpWebRequest)WebRequest.Create("http://Phone/LoginHandler.ashx");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0";
string requestForm = "Action=Phone_QueryMemberRemark&"+"userid="+userid+"&pageindex="+pageindex+"&pagesize="+pagesize;
byte[] postdatabyte = Encoding.UTF8.GetBytes(requestForm);
request.ContentLength = postdatabyte.Length;
request.AllowAutoRedirect = false;
request.CookieContainer = cc;
request.KeepAlive = true;

Stream stream;
stream = request.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length); //
stream.Close();

//接收响应
response = (HttpWebResponse)request.GetResponse();
Console.WriteLine();

Stream stream1 = response.GetResponseStream();
StreamReader sr = new StreamReader(stream1);
var json = sr.ReadToEnd();
context.Response.Write(json);
}

这样前台普通写法就好了。


posted @ 2016-03-25 17:32  lijunmomo  阅读(371)  评论(0编辑  收藏  举报