douge7771 2017-07-10 17:14
浏览 20

在页面刷新之前无法运行javascript

I've started using ajax requests recently. I am making a mobile web application where I am to the request for data on PHP side server script. The javascript function is to automatically execute when the user navigates to the page. But the script seems not to run until I refresh the page, here is my javascript code.

<script>
    $( document ).ready(function(){

    Date.prototype.yyyymmdd = function() {

        var yyyy = this.getFullYear().toString();
        var mm = (this.getMonth()+1).toString();
        var dd  = this.getDate().toString();

        return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
    };

    function requestContent()   {

        var date = new Date();
        $.ajax({
            type:'POST',
            url:'php/app/adminTimeline.php',
            data:{
                date: date.yyyymmdd()
            },
            success: function(data) {
                if (data == '') {

                    alert("No data found!");
                } else {
                    //  $("#loading_spinner").css({"display":"none"});
                    $('#timeline-content').prepend(data);
                }
            },
            error: function(data)   {
               // $("#loading_spinner").css({"display":"none"});
                alert("Something went Wrong!");
            }
        });

    }

window.onload = requestContent();
});
</script>

The document.onready method and window.onload the method seems not to be working too. Ps: I have the Jquery library linked in the header too.

  • 写回答

2条回答 默认 最新

  • dongwei3151 2017-07-10 17:36
    关注

    The code window.onload=requestContent(); will execute when the window loads, not necessarily when the entire document has loaded.

    However where you create the date object, uses this, which executes after the document is fully loaded

    $(document).ready(function(){
        //Code
    });
    

    This means, that the POST request will be made once the window loads, which is before the document is fully loaded, thus, that date object will not exist until the page is refreshed, at which point the Javascript was likely cached. Also another answer (@sagid) pointed out, window.onload cannot be a returning value but must be a function.

    i.e.

    window.onload=function(){
        //Code
    };
    

    This means, your solution is to change window.onload=requestContent(); to

    $(document).ready(function(){
        requestContent();
    });
    

    Good luck!

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)