jquery合并了所有相同的请求?

  1. 后端端口:随机从数据库中获取一条数据;
  2. 前端:同一个循环中获取的10条都是相同的数据;
  3. 前端发了10个request,但是后台只收到一个请求,也只返回了一次
  4. 给前端接口的data中加一个不一样的序号参数之后就能正确获取10条随机的数据了
    猜测:jq的默认优化,导致所有相同的请求jq只发一遍,一个返回值赋予所有的请求;

问题: $.ajax是否有相关设置把这中合并相同请求的默认设置改掉
ps: 查阅jq文档后没有找到这项设置,附上代码,谢谢大家。

for( var i = 0; i < 10; ++i ) {
    $.ajax( {
        type: "get",
        url: "/getNickname",
        data: {
            //index: i //my solution
        },
        beforeSend: function ( request ) {

        },
        success: function ( res ) {
            console.log( "test response is ", JSON.stringify( res ) );
        },
        error: function ( err ) {
            reject( err );
        }
    } );
}
//below is the function to get a random column from table
function getNicknameFromDB() {
    return new Promise( ( resolve, reject ) => {
        pg_pool.query( "select nickname from robot_nick_datas offset random() * (select count(*) from robot_nick_datas) limit 1;", (err, result)=> {
            if( err ){
                console.error( "query error: ", err );
                reject(err);
            }
            let nickname = Array.from(result.rows)[0];
            // console.log( "nick from database is ", nickname );
            resolve( nickname );
        } )
    } );
}
//below is the response
test response is  "{\"nickname\":\"caro\"}"
test response is  "{\"nickname\":\"caro\"}"
test response is  "{\"nickname\":\"caro\"}"
test response is  "{\"nickname\":\"caro\"}"
test response is  "{\"nickname\":\"caro\"}"
test response is  "{\"nickname\":\"caro\"}"
test response is  "{\"nickname\":\"caro\"}"
test response is  "{\"nickname\":\"caro\"}"
test response is  "{\"nickname\":\"caro\"}"
test response is  "{\"nickname\":\"caro\"}"
阅读 3.4k
2 个回答

被大佬解惑,是因为jQ缓存了GET请求的结果,这里贴上大佬的回答,感谢JLRishe的回复:
Most likely, the response is being cached because it is a GET request. Try telling jQuery to disable the cache:

$.ajax( {

type: "get",
url: "/getNickname",
cache: false,          // <--- here
data: {
    //index: i //my solution
},
beforeSend: function ( request ) {

},
success: function ( res ) {
    console.log( "test response is ", JSON.stringify( res ) );
},
error: function ( err ) {
    reject( err );
}

} );

另付jq文档关于cache选项的说明:
cache (default: true, false for dataType 'script' and 'jsonp')
Type: Boolean
If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

你猜

for (var i=0;i<5;i++) {
  setTimeout(function () {
    console.log(i)
  })
}

会输出什么??

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题