问题场景
jquery ajax,非jsonp请求,post数据中json包含多个问号,比如“{“a”:“aa??”}”。
请求时前端报错,由于jsonp的参数加到了post数据中的??位置,就无法通过url传入了。
报错信息(生产环境)
"parsererror" SyntaxError: Unexpected token ':'at eval (<anonymous>)at eval (jquery.js:339)at Function.globalEval (jquery.js:340)at text script (jquery.js:9773)at ajaxConvert (jquery.js:8843)at done (jquery.js:9260)at XMLHttpRequest.callback (jquery.js:9720) "{}"
或者(开发环境)
"parsererror" Error: jQuery111009581711862361235_1597629221274 was not calledat Function.error (jquery.js?1157:248)at s.converters.script json (jquery.js?1157:9893)at ajaxConvert (jquery.js?1157:8843)at done (jquery.js?1157:9260)at HTMLScriptElement.script.onload.script.onreadystatechange (jquery.js?1157:9831) "{}"
问题原因
我们找到jquery的这段代码
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {var callbackName, overwritten, responseContainer,jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?"url" :typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data");
看到如果data中存在??这种特殊写法,rjsonp.test( s.data )返回true,最终将"data"赋值给jsonProp。
而data中不存在??就会给jsonProp赋值为false。
如果jsonProp=“data”
那么会走到这段代码里面
// Handle iff the expected data type is "jsonp" or we have a parameter to setif ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {// Get callback name, remembering preexisting value associated with itcallbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?s.jsonpCallback() :s.jsonpCallback;// Insert callback into url or form dataif ( jsonProp ) {s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );} else if ( s.jsonp !== false ) {s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;}
由于这行代码s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, “$1” + callbackName );
最终data中的??会被替换为callbackName,可以监听发现这个异常现象。
替换了这里就不会走下面的s.url的常规jsonp参数赋值到url的处理了,所以导致异常的发生。
解决办法
让特殊data的jsonProp=false,我们从jsonProp = s.jsonp !== false这块入手,调用ajax时:
$.ajax传参时jsonp: false赋值,这样jsonProp直接赋值为false,不走正则检测,就不会出问题了。
那么如果跨域怎么办呢?
这个可以采用服务端加跨域header解决。