Home > Software design >  How to change $(document).ready (function) to onload special tag in order to pass variable to js fun
How to change $(document).ready (function) to onload special tag in order to pass variable to js fun

Time:05-27

Each of them supposed to show a value from database when the page loads. So I wrote three $(document).ready(function) with three input for GET controller value. I know they run parallel maybe it is good but I want to see if I wrote only one function (design it Linear) with an input value to pass to GET method, I get higher performance or not.

I change the code bellow :

$(document).ready(function () {
    $.ajax({
        url: '/Home/GetData',
        data: { id: 1 },
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
            $('#result1').html(result);
        }
    });
});

to

function bringData(statusId) {
    $.ajax({
        url: '/Home/GetData',
        data: { id: statusId },
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
            $('#result1').html(result);
        }
    });
};  

and in my view I use onload="bringData(0)" like bellow :

      <div >
            <h3 ><span id="result1"  onl oad="bringData(0)"></span><sup 
            style="font-size: 20px"></sup></h3>
            <p>Commited Orders</p>
        </div>

but when I run the code it doesn't show the value?

CodePudding user response:

onload is not a global attribute you can't just stick it on any element and expect it to work.

What you should have done was call bringData from the ready function:

$(document).ready(function () {
    bringData(0);
});

function bringData(statusId) {
    $.ajax({
        url: '/Home/GetData',
        data: { id: statusId },
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
            $('#result1').html(result);
        }
    });
};

If you insist on using an onload attribute, then it should be on the <body> tag

<body onl oad="bringData(0)">
    ...
</body>
  • Related