如何使用Jquery在Javascript中加载页面时调用函数

时间:2013-12-03 03:00:28

标签: javascript jquery html pageload

<script type="text/javascript" >

        function getDetails() {
            var IDex = getQueryStringVariableByName("GameID");

            $.ajax({
                type: "POST",
                url: "http:/...",
                data: "{'ItemID': '" + escape(IDex) + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var data = response.d;
                    $('#output').empty();
                    $.each(data, function (index, item) {
                        var str = "Title: " + item.Name + "<br /> Current Price: " + item.CurrentPrice + "<br /> Developer: " + item.Developer + "<br /> Genres: " + item.Genre
                        $('#output').append('<li>' + str + '</li>');
                    });
                },
                failure: function (msg) {
                    $('#output').text(msg);
                }
            });
        }


         function getQueryStringVariableByName(name) {
             //use this function by passing it the name of the variable in the query
             //string your are looking for.  For example, if I had the query string
             //"...?id=1" then I could pass the name "id" to this procedure to retrieve
             //the value of the id variable from the querystring, in this case "1".
             name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
             var regexS = "[\\?&]" + name + "=([^&#]*)";
             var regex = new RegExp(regexS);
             var results = regex.exec(window.location.search);
             if (results == null)
                 return "";
             else
                 return decodeURIComponent(results[1].replace(/\+/g, " "));
         }

         window.onload = GetDetails;
         //$(document).ready( function () {
         //    getDetails();
         //
</script>

我已经尝试了多种方法来在页面加载时运行getDetails。我已经尝试了window.onload方法,将它放在body标签中,还有其他几个,但我似乎找不到让它自动加载的方法。

5 个答案:

答案 0 :(得分:1)

它应该是getDetails,或者您可以使用:

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

答案 1 :(得分:1)

检查编译器在页面加载时是否实际读取代码

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

function getDetails() { 
   alert("this is a try");
   //or
   console.log("this is a try");
}

当然包括jquery框架到您的文档,如

<script src = "path" type = "text/javascript"></script>

最好的方法是在必须关闭正文标记

之前编写它

希望它有所帮助!

答案 2 :(得分:0)

我不确定我是否理解这个问题,但在jQuery加载页面后运行函数的方法是:

$(document).ready(function() {

    // Your code goes here..
    myFunction();

});

答案 3 :(得分:0)

它不起作用?

$(function(){
         getDetails();
    });

答案 4 :(得分:0)

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

肯定会有用。