本文针对前端开发中两个常见且隐蔽的问题提供解决方案。首先分析IE7浏览器对GET请求URL长度超过2032字符导致的HTTP Status 122报错,建议将JSONP GET改为常规POST方法。其次探讨Ajax回调中this指向window而非对象本身的问题,通过保存this引用至局部变量(如thisValue)来正确访问对象属性。
在开发项目时,前端常会遇到一些较为隐蔽的技术问题。
IE7 GET请求长度限制处理
问题一:针对IE7浏览器,处理GET传输值过长引发的HTTP Status 122报错。
原因:在IE[[wp:a6.8]]下没有什么问题,但在IE7就不兼容get参数过长,google上说“Don't use the GET method in Ajax Apps, if you can void it, because IE7 craps out with more than 2032 characters in a get string”
解决方法:
将原项目中采用JSONP GET方式获取数据的逻辑,改为常规的POST数据提交方法。
Ajax回调中this作用域修复
问题二:JavaScript中this作用域的指向问题。
原因分析:如果this不在对象内部定义,默认指向window这个大对象。例如,当this出现在Ajax请求内部时,它指的是当前域名的Ajax对象,而非外层对象。
解决方法:
参考代码如下:
var test={};
test.getflash = 2;
test.test =function(){
alert(this.getflash); //输出2
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert(this.getflash); //输出undefined
}
});
} 解决方法:
参考代码如下:
test.test =function(){
var thisValue = this;
alert(thisValue.getflash); //输出2
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert(thisValue.getflash); //输出2
}
});
}