关于IEajaxpost请求无法获取数据的BUG

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sinat_39826352/article/details/77141468

关于IEajaxpost请求无法获取数据的BUG

问题描述:上个星期接手了一个网站,要求兼容ie,使用的是jquery,其中获取数据的部分采用了jquery的ajax方法。但是问题来了,我用post请求拿回了数据,并且在chrom,firefox和ie10+浏览器上使用时都没有问题。

但是但是当我在ie9及以下浏览器测试的时候,发现数据没了,(我去,这不科学啊),难道是我写错了?

于是我果断跟换了jquery版本,将其降到了1.8.3(兼容ie算是稳定版本),但是依然没有结果.(见到鬼了吧)。

  • 后来经过反复研究终于找到了问题所在,就是IE9及以下浏览器存在跨域问题,没办法,只有让后台的哥们进行处理了。

  • 最后在后台哥们的配合下终于解决了问题:具体解决方案就是让后台进行跨域处理,直接前台不用跨域,这样就可以完美解决了。

添加代码如下:

response.addHeader("Access-Control-Allow-Origin", "*");   //用于ajax post跨域(*,最好指定确定的http等协议+ip+端口号)
展开阅读全文

post请求获取数据

07-20

[img=https://img-bbs.csdn.net/upload/201807/20/1532060550_696181.png][/img]rn[img=https://img-bbs.csdn.net/upload/201807/20/1532060559_174959.png][/img]rn[img=https://img-bbs.csdn.net/upload/201807/20/1532060567_176628.png][/img]rn[code=csharp]rnstring Url = "http://www.szbjh.com:8114/Enjoy/Service/";rn string st = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff");rn st = st.Replace(" ", "T") + "Z";rn Dictionary PostPara = new Dictionaryrn rn "UniqueKey","EnjoySCM40通用",rn "MethodName","GetPartnerMenu",rn "UserNo","",rn "ClientTime",st,rn "ObjectData","003693",rn "Tag",null,rn "Token","token-null"rn ;rn //这个Cookies我上面的代码登录确保已经获取到了rn string json = HttpResponse.PostHttpResponseJson(Url, null, PostPara, Cookies);rn[/code]rnrn[code=csharp]rnpublic static string PostHttpResponseJson(string url, IWebProxy webProxy, Dictionary postDict, CookieCollection Cookie)rn rn string json = string.Empty;rn Encoding encoding = Encoding.UTF8;rn HttpWebResponse Response = CreatePostHttpResponse(new HttpPostParametersModel()rn rn Url = url,rn DictParameters = postDict,rn WebProxy = webProxy,rn RequestEncoding = encoding,rn Cookies = Cookiern );rn json = GetStream(Response, encoding);rn return json;rn rn[/code]rnrn[code=csharp]rn /// rn /// 创建POST方式的HTTP请求rn /// rn /// 请求的URLrn /// 随同请求POST的参数名称及参数值字典rn /// 请求的超时时间rn /// 请求的客户端浏览器信息,可以为空rn /// 发送HTTP请求时所用的编码rn /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空rn /// rn public static HttpWebResponse CreatePostHttpResponse(HttpPostParametersModel postParametersModel)rn rn if (string.IsNullOrEmpty(postParametersModel.Url))rn rn throw new ArgumentNullException("postParametersModel.Url");rn rn if (postParametersModel.RequestEncoding == null)rn rn throw new ArgumentNullException("postParametersModel.RequestEncoding");rn rn HttpWebRequest request = null;rn //如果是发送HTTPS请求rn if (postParametersModel.Url.StartsWith("https", StringComparison.OrdinalIgnoreCase))rn rn ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);rn request = WebRequest.Create(postParametersModel.Url) as HttpWebRequest;rn request.ProtocolVersion = HttpVersion.Version11;rn rn elsern rn request = WebRequest.Create(postParametersModel.Url) as HttpWebRequest;rn rn if (postParametersModel.WebProxy != null)rn rn request.Proxy = postParametersModel.WebProxy;rn rn request.Method = "POST";rn request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";rnrn if (!string.IsNullOrEmpty(postParametersModel.UserAgent))rn rn request.UserAgent = postParametersModel.UserAgent;rn rn elsern rn request.UserAgent = DefaultUserAgent;rn rnrn if (postParametersModel.Timeout.HasValue)rn rn request.Timeout = postParametersModel.Timeout.Value;rn rn if (postParametersModel.Cookies != null)rn rn request.CookieContainer = new CookieContainer();rn request.CookieContainer.Add(postParametersModel.Cookies);rn rn //如果需要POST数据rn if (!(postParametersModel.DictParameters == null || postParametersModel.DictParameters.Count == 0))rn rn StringBuilder buffer = new StringBuilder();rn int i = 0;rn foreach (string key in postParametersModel.DictParameters.Keys)rn rn if (i > 0)rn rn buffer.AppendFormat("&0=1", key, postParametersModel.DictParameters[key]);rn rn elsern rn buffer.AppendFormat("0=1", key, postParametersModel.DictParameters[key]);rn rn i++;rn rn byte[] data = postParametersModel.RequestEncoding.GetBytes(buffer.ToString());rn using (Stream stream = request.GetRequestStream())rn rn stream.Write(data, 0, data.Length);rn rn rn return request.GetResponse() as HttpWebResponse;rn rn[/code]rnrn[code=csharp]rn/// rn /// 将response转换成文本rn /// rn /// rn /// rn /// rn private static string GetStream(HttpWebResponse response, Encoding encoding)rn rn tryrn rn if (response.StatusCode == HttpStatusCode.OK)rn rn switch (response.ContentEncoding.ToLower())rn rn case "gzip":rn rn string result = Decompress(response.GetResponseStream(), encoding);rn response.Close();rn return result;rn rn default:rn rn Byte[] buffer = new Byte[response.ContentLength];rn using (StreamReader sr = new StreamReader(response.GetResponseStream(), encoding))rn rn string result = sr.ReadToEnd();rn sr.Close();rn sr.Dispose();rn response.Close();rn return result;rn rn rn rn rn elsern rn response.Close();rn rn rn catch (Exception e)rn rn throw e;rn rn return "";rn rn[/code]rnrn[code=csharp]rnprivate static readonly string DefaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0";rnrn /// rn /// GET请求参数模型rn /// rn public class HttpGetParametersModelrn rn /// rn /// 请求的URL(GET方式就附加参数)rn /// rn public string Url get; set; rnrn /// rn /// 超时时间rn /// rn public int? Timeout get; set; rnrn /// rn ///浏览器代理类型rn /// rn public string UserAgent get; set; rnrn /// rn /// Web请求代理rn /// rn public IWebProxy WebProxy get; set; rnrn /// rn /// Cookies列表rn /// rn public CookieCollection Cookies get; set; rn rnrn /// rn /// POST请求参数模型rn /// rn public class HttpPostParametersModel : HttpGetParametersModelrn rn /// rn /// POST参数字典rn /// rn public IDictionary DictParameters get; set; rnrn /// rn /// 发送HTTP请求时所用的编码rn /// rn public Encoding RequestEncoding get; set; rn rn[/code]rn[code=text]rnrn "ObjectData": null,rn "UniqueKey": null,rn "MethodName": null,rn "SourceMethodName": null,rn "Tag": null,rn "UserState": null,rn "Exception": rn "HasException": true,rn "ExceptionType": 0,rn "Code": "-1",rn "Message": "Unexpected character encountered while parsing value: U. Path '', line 0, position 0.",rn "StackTrace": " 在 Newtonsoft.Json.JsonTextReader.ParseValue()\r\n 在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)\r\n 在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\r\n 在 Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\r\n 在 Enjoy.Common.JsonHelper.DeserializeObject[T](String JSON)\r\n 在 Enjoy.EnjoyRun.Run(String request, String& response)\r\n 在 Enjoy.EnjoyRun.Run(String request)"rn ,rn "HasException": truernrn[/code]rn我想请求出来的就是最后一张图片的json数据,但是好像中间出了点问题。请求出来数据的格式好像是对的,但是就是"ObjectData": 里面没有数据,而且下面还报错了。 论坛

uploadify+struts2 ACTION无法获取数据

02-17

uploadify build: 3.2.1rnrn核心代码rnhtml: rn 上传证件: rn 开始上传| rn 取消上传rn 支持上传的类型:png、jpg、gif、jpeg。rnjs:$("#uploadify").uploadify(rn 'method':"post",rn 'uploader':tool.getRootPath()+"upload/uploadimg.action",rn 'swf' : tool.getRootPath()+"static/plugins/uploadify/uploadify.swf",rn //'checkExisting' :tool.getRootPath()+"upload/uploadimg.action",rn //'buttonImage': tool.getRootPath()+"static/plugins/uploadify/uploadify-cancel.png",rn 'fileSizeLimit' : '1MB',rn 'fileTypeExts' : '*.gif; *.jpg; *.png; *.jpeg',rn 'fileTypeDesc' : "支持上传的类型:gif、jpg、png、jpeg",rn 'queueID': 'fileQueue',rn 'auto' : false,rn 'multi' : true,rn 'simUploadLimit' : 2,rn 'removeTimeout' : 10,rn 'buttonText' : '浏览'rn );rnjava action:rnpublic class UploadAction extends BaseAdminActionrn private static Logger logger = Logger.getLogger(UploadAction.class);rn private File uploadify;rn private String uploadifyFileName;rn private String filepath;rn /**rn * 上传图片rn * @return 图片路径rn */rn @Action(value="uploadimg",results=@Result(name="uploadimg",type="json",params="root","filepath"))rn public String uploadimg()rn String savePath = ServletActionContext.getServletContext().getRealPath("/UploadFile");//上传完后文件存放位置 rn System.out.println(savePath); rn String newsuffix = ""; rn String current=new java.text.SimpleDateFormat("yyyyMMdd").format(new Date());rn if((uploadifyFileName != null)&&(uploadifyFileName.length()>0)) rn rn int dot = uploadifyFileName.lastIndexOf("."); rn if((dot >-1) && (dot < (uploadifyFileName.length() - 1))) rn rn newsuffix = uploadifyFileName.substring(dot + 1); rn rn rn try rn FileInputStream fis = new FileInputStream(uploadify);rn filepath = savePath+"/"+current + "." + newsuffix;rn FileOutputStream fos = new FileOutputStream(filepath); rn IOUtils.copy(fis, fos); rn fos.flush(); rn fos.close(); rn fis.close(); rn catch (Exception e) rn logger.error("图片上传错误", e);rn filepath="";rn rn return "uploadimg";rn rn在进入uploadimg方法时 uploadify,uploadifyFileName为NULL 求小伙伴们指点rn[img=https://img-bbs.csdn.net/upload/201402/17/1392622172_118701.jpg][/img]rn 论坛

(新手求救)无法获取数据

11-27

string act = q("act");rn string diPage = q("page");rn int pageRecord = 5;rn rn doh.Reset();rn doh.SqlCmd = "select * from xk_liuyan order by id desc";rn DataTable dt = doh.GetDataTable();rn rn // DataSet dt = doh.GetDataSet();rn if (act.Trim() == "pageinfo")rn rn rn response = dt.Rows.Count + "|" + pageRecord + "|" + Math.Ceiling(Convert.ToDouble(dt.Rows.Count)/Convert.ToDouble(pageRecord)) + "|" + Session["CurPage"];rn //dt.Clear();rn return;rn rn rn rn if(diPage=="undefined"&Session["CurPage"]!="")rn rn diPage=Session["CurPage"].ToString();rn rn int page = int.Parse(diPage);rn Session["CurPage"]=diPage;rn int start_jilu = (page - 1) * pageRecord;rn int end_jilu = page * pageRecord;rnrn rn if (end_jilu > dt.Rows.Count)rn end_jilu = dt.Rows.Count;rn for (int i = start_jilu; i < end_jilu; i++)rn // for (int i = 0; i < 5; i++)rn rn string tempstr = "username:" + '"' + dt.Rows[i][1].ToString() + '"' + ",sex:" + '"' + dt.Rows[i][2].ToString() + '"' + ",qq:" + '"' + dt.Rows[i][3].ToString() + '"' + ",email:" + '"' + dt.Rows[i][4].ToString() + '"' + ",content:" + '"' + dt.Rows[i][5].ToString() + '"' + ",huifu:" + '"' + dt.Rows[i][8].ToString() + '"' + ",pubdate:" + '"' + dt.Rows[i][6].ToString() + '"' + ",";rn response += tempstr;rn // response = "获取留言成功";rn //dt.Clear();rn rn if(response!="")rn rnrn response=response.TrimEnd(',');rn rn elsern rn response="0";rn rn rn // response = "获取留言成功";rnrnrn据留言条数,有时能加载留言,有时不能 ,请兄弟忙帮忙看看!rn 论坛

ajax问题,无法获取数据

07-09

我新建了一个查询页(Select.aspx)和一个获取查询结果的页(GetSelectData.aspx)rn下面是select.aspx的js代码:rn[code=JScript]rnvar xmlhttp;rnfunction GetData()rnrn var time=document.getElementById("<%=TimeTB.ClientID%>").value;rn var scity=document.getElementById("<%=SCityTB.ClientID%>").value;rn var dcity=document.getElementById("<%=DCityBT.ClientID%>").value;rn if(window.ActiveXObject)rn rn xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器rn rn else if(window.XMLHttpRequest)//非IE浏览器rn rn xmlhttp=new XMLHttpRequest();rn rn elsern rn alert("创建XMLHttpRequest对象失败!");rn return;rn rn xmlhttp.Open("GET","GetSelectData.aspx?stime="+time+"&scity="+scity+"&dcity="+dcity,false);rn xmlhttp.onreadystatechange=handlfunc;rn xmlhttp.send(null);rnrnrnfunction handlfunc()//获取数据后处理函数rnrn if(xmlhttp.readystate==4)rn rn if(xmlhttp.status==200)rn rn var data=bytes2BSTR(xmlhttp.ResponseBody);rn var start=data.indexOf("查找结果");rn var end=data.indexOf("结束");rn var finaldata=data.substring(start+8,end);rn document.write(xmlhttp.ResponseText);rn //document.getElementById('data_div').innerHTML=data;rn //document.getElementById("data_div").innerHTML=xmlhttp.ResponseText;rn rn rn rnrn[/code]rnGetSelectData.aspx页面的后台代码:rn[code=C#]rn protected void Page_Load(object sender, EventArgs e)rn rn string time = "2009-08-05",scity="南昌",dcity="景德镇";rn if (!IsPostBack)rn rn tryrn rn time = Request.QueryString["stime"].ToString();rn scity = Request.QueryString["scity"].ToString();rn dcity = Request.QueryString["dcity"].ToString();rn rn catch (Exception ex)rn rn Response.Redirect("ErrorPage.htm");rn rn LoadData(time, scity, dcity);rn rn rn rn public void LoadData(string time,string scity,string dcity)rn rn SqlParameter[] sp =DBAccess.MakeParam("@stime",SqlDbType.VarChar,time),rn DBAccess.MakeParam("@scity",SqlDbType.VarChar,scity),rn DBAccess.MakeParam("@spoint",SqlDbType.VarChar,""),rn DBAccess.MakeParam("@dcity",SqlDbType.VarChar,dcity),rn DBAccess.MakeParam("@dpoint",SqlDbType.VarChar,"")rn ;rn int flag = 0;rn DataView dv = DBAccess.GetData("qiche_SelectBusInfo", sp, out flag).Tables[0].DefaultView;rn if (flag == 11)rn rn Response.Redirect("ErrorPage.htm");rn rn this.DataList1.DataSource = dv;rn this.DataList1.DataBind(); rn rn[/code]rn现在问题,当输入查询条件时,无查询到数据,得到是GetSelectData.aspx页面没绑定数据时的东西.rn还有就当用responsebody时,出现乱码,如何解决。rn小弟,刚开始弄这个ajax这个东东。有很多不懂,现在是一头雾水。 论坛

没有更多推荐了,返回首页