关于ajax 跨域调用接口

本文介绍两种实现跨域请求的方法:一种是使用JSONP进行GET请求,另一种是通过创建ASHX文件并利用HTTPWebRequest实现POST请求。文中详细展示了前后端的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:

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

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


转载于:https://www.cnblogs.com/lijun2013/p/5320345.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值