连续ajax请求数据混乱,关于jquery:jQuery-Ajax-Post请求连续多个问号特殊数据异常问题...

博客讲述了在使用jQuery AJAX进行POST请求时,如果JSON数据包含问号导致的parsererror错误。问题源于jQuery的jsonp处理方式,当data中存在问号时,jQuery会尝试将其作为jsonp回调函数名,从而引发错误。解决方案是设置`jsonp: false`以避免此行为,同时可以通过服务端添加跨域头来解决跨域问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题场景

jquery ajax,非jsonp申请,post数据中json蕴含多个问号,比方“{“a”:“aa??”}”。

申请时前端报错,因为jsonp的参数加到了post数据中的??地位,就无奈通过url传入了。

报错信息(生产环境)

"parsererror" SyntaxError: Unexpected token ':'

at eval ()

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 called

at 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) "{}"

或者(后盾接收数据)

前端发送的含 ?? 的字符变成相似 jQuery183554546_6546423242342 模式的字符。

问题起因

咱们找到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 set

if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

// Get callback name, remembering preexisting value associated with it

callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?

s.jsonpCallback() :

s.jsonpCallback;

// Insert callback into url or form data

if ( 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解决。

参考:https://blog.csdn.net/whq12789/article/details/108050349

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值