zoukankan      html  css  js  c++  java
  • 关于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);
    }

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


  • 相关阅读:
    SGU 107
    HDU 1724 自适应辛普森法
    POJ 1061 扩展欧几里得
    zzuli2424: 越靠近,越幸运(dfs)
    zzuli1519: 小P参加相亲大会(异或)
    zzuli1519: 小P参加相亲大会(异或)
    牛客练习赛42 A:字符串
    牛客练习赛42 A:字符串
    zzuli1511: 小P的loI
    zzuli1511: 小P的loI
  • 原文地址:https://www.cnblogs.com/lijun2013/p/5320345.html
Copyright © 2011-2022 走看看