IE下ajax返回值为json弹出下载框的方法总结

来源:互联网 发布:linux jdk tar安装 编辑:程序博客网 时间:2024/06/06 14:10

    近日因为项目要求兼容IE7, 不得不修改上传图片的插件(由uploadify改为ocupload)。几经周折终于搞定上传功能,在chrome, ff测试都通过,偏偏在IE7会因为返回值是json, 会弹出下载框。(本机只有原生IE7, 未能测试IE8是否有该问题, 据说IE9及以上是已经支持json格式的)。当然网上还是有大把的解决方案的,个人测试后觉得最靠谱的还是:ContentType设置为text/plain。项目使用的是springMVC,具体代码如下:

package cn.***.saas.util;import net.sf.json.JSONObject;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import cn.***.saas.constant.ResponseCode;import cn.***.saas.constant.ResponseStatus;public class ResponseUtilForIe {    public static final String RESPONSE_BODY = "body";    public static final String RESPONSE_STATUS = "status";    public static final String RESPONSE_ERROR = "error";    public static final String RESPONSE_ERROR_CODE = "code";    public static final String RESPONSE_ERROR_MSG = "msg";    public static ResponseEntity<String> jsonSucceed(Object object, HttpStatus statusCode) {        JSONObject jo = new JSONObject();        Object responseBody = DataUtil.formatApiResponse(object);        jo.accumulate(RESPONSE_BODY, responseBody);        return wrapResponse(ResponseStatus.SUCCEED, jo, statusCode);    }    public static ResponseEntity<String> jsonFailed(String errorMessage, HttpStatus statusCode) {        return jsonFailed(errorMessage, ResponseCode.SERVER_ERROR, statusCode);    }    public static ResponseEntity<String> jsonFailed(Object errorMessage, ResponseCode code, HttpStatus statusCode) {        JSONObject errorObj = new JSONObject();        errorObj.accumulate(RESPONSE_ERROR_CODE, code.getValue());        errorObj.accumulate(RESPONSE_ERROR_MSG, errorMessage);        JSONObject error = new JSONObject();        error.accumulate(RESPONSE_ERROR, errorObj);        JSONObject jo = new JSONObject();        jo.accumulate(RESPONSE_BODY, error);        return wrapResponse(ResponseStatus.FAILED, jo, statusCode);    }    private static ResponseEntity<String> wrapResponse(ResponseStatus status, JSONObject body, HttpStatus statusCode) {        HttpHeaders headers = new HttpHeaders();        headers.set("Content-Type", "text/plain;charset=UTF-8");        if (ResponseStatus.SUCCEED.equals(status)) {            body.accumulate(RESPONSE_STATUS, ResponseStatus.SUCCEED.toString());        } else if (ResponseStatus.FAILED.equals(status)) {            body.accumulate(RESPONSE_STATUS, ResponseStatus.FAILED.toString());        }        return new ResponseEntity<String>(body.toString(), headers, statusCode);    }}
在上传图片的controller方法里,返回值直接使用方法即可。


此外也有说通过修改注册表的, 方法是: 在注册表中添加如下项:

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]    "CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"    "Encoding"=dword:00080000      [HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]    "CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"    "encoding"=dword:00080000 
或者直接将上述代码保存为.reg文件,双击执行即可。不过本人未曾试过此方法,因为对于web项目,不可能要求或者强制用户都修改注册表。



原创粉丝点击