简体   繁体   中英

Insert Javascript Function Value in Partial View

I have a javascript function which returns a value that I am trying to display in a table in my partial view.

In my main view I have something like this:

<script type="text/javascript">
    function myFunc(i) 
    {
        var url = '/myurl/?id=' + i;

        $.getJSON(url)
        .done(function (data) 
        {
            return data;
        }
    }
</script>

In my partial view html I am trying to do this:

<td><script>document.write(myFunc())</script></td>

The function gets called but it seems to always return undefined am I doing something wrong here?

This is because you are not passing parameter in function and function aspect parameter.. which is null at this stage.

  • your call ...

    document.write(myFunc())

  • and your Function

    function myFunc(i)

  • so your URl become

    var url = '/myurl/?id=' + Null; // some thing like this

so URL is not correct and hence not getting correct data

Silly me, once I realized this was an asynchronous issue the solution was obvious and I should have done this in the first place...

<script type="text/javascript">
    function myFunc(i) 
    {
        var url = '/myurl/?id=' + i;

        $.getJSON(url)
        .done(function (data) 
        {
            document.getElementById("myDiv").innerHTML = data;
        }
    }
</script>

This did the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM