項目中遇到一個只在 IE10+ 出現的怪問題:表單上傳文件後,後端返回的 JSON 數據沒有被前端插件正常解析,反而被瀏覽器彈出了「文件下載」提示。
前端用的是 jQuery 的 ajaxForm 插件提交表單,後端返回的數據格式為 JSON。關鍵在於插件配置裡開啟了 iframe: true——為了支援文件上傳,ajaxSubmit 會退化成通過隱藏 iframe 提交表單,響應文檔被載入 iframe 中,再由插件從中取出內容。而當響應的 MIME 類型是 application/json 時,IE10 及以上的版本會把這個響應視為可下載對象,直接觸發下載對話框,而不是把它當作文檔渲染進 iframe。
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
temp_content = func(*args, **kwargs)
if isinstance(temp_content, dict):
temp_content.setdefault('success', True)
temp_content.setdefault('code', 200)
try:
temp_content = json.dumps(temp_content, indent=4)
except UnicodeDecodeError:
try:
temp_content = ujson.dumps(temp_content)
except StandardError as e:
logger.exception(e)
temp_content = json.dumps({'success': False, 'code': 500, 'info': 'INVALID_CONTENT'})
temp_content = cgi.escape(temp_content)
if callback:
# jsonp 添加 /**/ 頭部會安全一些
content = '/**/' + str(callback) + '(' + temp_content + ')'
mimetype = 'application/javascript'
headers = {'charset':'utf-8'}
return current_app.response_class(content, mimetype=mimetype, headers=headers)
else:
mimetype = 'application/json'
headers = {'charset':'utf-8'}
content = temp_content
return current_app.response_class(content, mimetype=mimetype, headers=headers)
elif isinstance(temp_content, basestring):
temp_content = cgi.escape(temp_content)
return temp_content
else:
return temp_content
return decorated_function
@mod.route('/patch/install.json', methods=['POST'])
@jsonp
def patch_install():
return {'data': 'data'}
$('#form').ajaxSubmit({
url : '/patch/install.json',
type : 'post',
dataType : 'json',
iframe : true,
success: function(res) {
// code
}
});
只需要讓後端返回的 Content-Type 變成 text/html,瀏覽器就會老老實實把響應體當作文檔載入 iframe,插件也能正常取出內容解析:
def plain(func):
"""wrap text/html response"""
@wraps(func)
def _inner(*args, **kwargs):
resp = func(*args, **kwargs)
if isinstance(resp, dict):
resp.setdefault('success', True)
resp.setdefault('code', 200)
resp = json.dumps(resp)
resp = cgi.escape(resp)
return current_app.response_class(resp, mimetype='text/html', headers={'charset': 'utf-8'})
elif isinstance(resp, basestring):
resp = cgi.escape(resp)
return current_app.response_class(resp, mimetype='text/html', headers={'charset': 'utf-8'})
else:
return resp
return _inner
@mod.route('/patch/install.json', methods=['POST'])
@plain
def patch_install():
return {'data': 'data'}
注意:此例後端使用的是 Python,若你的項目遇到同樣問題,把相應改動換成自己所用的語言即可。
總結起來其實就一句話——把後端返回的數據格式改成 text/html。另外值得一提的是,cgi.escape 在這裡承擔了轉義的職責,避免響應內容中的特殊字符破壞 HTML 文檔結構,這個細節不能省。