$ .ajax请求无法首次加载页面 [英] $.ajax request fails for first call on page load

查看:210
本文介绍了$ .ajax请求无法首次加载页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码片段,我在其中通过$.ajax从后端节点服务器提取所有配置.但是,当我第一次点击我的页面时,没有得到响应,就像当我检查节点服务器上的登录时,我确实看到请求的状态为200 Ok.但是我刷新页面两次或三次,但是我没有得到正确的响应.

I have code snippet where I am pulling all the configs from back-end Node server through $.ajax. But when I hit My page first time, I do not get the response, where as When I check the log on node server, I do see the status for the request as 200 Ok. But I refresh the page twice or thrice I get the response properly.

下面是我的代码:

var appConfig = getConfig();
function setAppConfig(){
    var url = env.NEW_SERVER_URL + '/api/client/getConfig/carrier/';
    $.ajax({
        type: 'GET',
        contentType: "application/json",
        url: url,
        success: function (response) {
            //   console.log(response);
            var configData = JSON.stringify(response);
            sessionStorage.setItem('config', configData);
            return true;
        },
        error: function (error) {
            console.log("some error in connection with server");
            return false;
        }
    });
}

function getConfig(){
    var appConfig = "";
    // console.log(fetchFromSession('config'));
    if(fetchFromSession('config') !== null){
        appConfig = JSON.parse(fetchFromSession('config'));
    }else{
        if(setAppConfig()){
            appConfig = JSON.parse(fetchFromSession('config'));
        }else{
            console.log('Something went wrong in pullling the configs');
        }
    }
    return appConfig;
}

节点服务器代码以响应获取请求:

exports.config = ((req, res,next) => {
    let carrier = req.params.carrier;
    logger.info("getConfig started", {carrier: carrier});

     if(carrier){
          var msg = require(path.join('./../../../config/',carrier,'/config.json'));
          logger.info("Response for getScripts", {carrier: carrier, response: msg});
          res.send(msg);
     }
})

此脚本首先在页面上加载,所有相关脚本都标记为defer以等待其加载

This script is loaded first on the page and all the dependent scripts are marked defer to wait for it to get loaded

问题:

  • 我的代码有什么问题?
  • 为什么它第一次不起作用,但是之后却可以刷新页面?
  • 我需要做些什么才能在首次加载时获得成功的响应?

推荐答案

请尝试使用POST方法使用此

喜欢

$.ajax({ type: "POST", async: true, cache: false,

$.ajax({ type: "POST", async: true, cache: false,

这篇关于$ .ajax请求无法首次加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆