简体   繁体   中英

Advice requested - passing variables between functions using json/jquery & ajax

I've looked over a lot of 'similar' q&a threads on SO but to be honest, as I don't have too much of a grip on js programming, I'm finding it difficult to make sense of a lot of the answers (as far as they may apply to my own situation).

The context is this, I have two php scripts one returning a list of customer_ids (json encoded) for a set period and the other returning their preferences for news feeds (json encoded).

I wrote the following, having googled a bit to get a basic understanding of how to setup an ajax function in jQuery:

$('document').ready(function() {
    $.ajax({
        type:'GET', url: 'cust_selection.php', data: '',
        succes:function(cstmrid) {
            var clistlen = cstmrid.length;
            var i=0;
            var cstmr;
            for( ;cstmr=cstmrid[i++]; ) {
            $('#adminPanel>ul>li').append("<a href='' onclick='alert("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>"); //alert to be replaced with a function call which passes customerid to the function below.
            }
        },
        dataType:'json'
    });

    var cstmrid = "483972258"; //hardcoded for testing purposes
    $.ajax({
        type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
        success:function(npfdata) {
            var item;
            var n=0;
            for( ;item=npfdata[n++]; ) {
                var news = npfdata[n].nsource;
                $('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
            }
         },
         dataType:'json'
    });
});

Now from the first ajax function, I get a list of links which I want to be able to click to launch the second ajax function and pass it the customer id so that it can grab a list of the news sources that they've configured for their pages. The alert and the hard-coded customer id both suggest that the functions are 'working', but when I try and adjust the first function so that: ...

$('#adminPanel>ul>li').append("<a href='' onclick='getCustomerNP("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>");

... is calling a modified version of the second function, as below: ...

function getCustomerNP(cstmrid) {
    $.ajax({
        type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
        success:function(nprfdata) {
            var item;
            var n=0;
            for( ;item=npfdata[n++]; ) {
                var news = npfdata[n].nsource;
                $('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
            }
         },
         dataType:'json'
    });
}

Everything seems to just fail at this point. The second function doesn't seem to 'receive' the variable and I'm not sure if it's something elementary that I've overlooked (like some muddled up " and ' placements) or if what I am trying to accomplish is actually not the way jQuery ajax functions interact with each other.

As you can see, I've cannibalised bits of code and ideas from many SO q&a threads, but copying without much of an understanding makes for a frustratingly dependent life.

I would appreciate as much - expansive - comment as you can provide, as well as a solution or two (naturally).

EDIT: Not to confuse anyone further, I've been modifying the above and correcting my (many) errors and typos along the way. At present, the code looks like below:

$('document').ready(function () {
    $.ajax({
        type: 'GET', url: 'cust_selection.php', data: '',
        succes: function (cstmrid) {
            var clistlen = cstmrid.length;
            var i = 0;
            var cstmr;
            for (; cstmr = cstmrid[i++]; ) {
                var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
                    getCustomerNP(cstmr)
                })
                $('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
            }
        },
        dataType: 'json'
    });
    function getCustomerNP(cstmr) {
        alert(cstmr);
    }
});

You've got a typo in the $.ajax() success function within getCustomerNP() . The function declaration:

success:function(nprfdata) {

... has a parameter nprfdata , but then within the function you use npfdata (missing the r ).

Also this code:

        var item;
        var n=0;
        for( ;item=npfdata[n++]; ) {
            var news = npfdata[n].nsource;
            $('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
        }

...declares and sets variable news that you never use. And it doesn't seem right to increment n in the for test expression but then use n within the loop. You never set item to anything but you use it in your .append() .

(Note also that JS doesn't have block scope, only function scope, so declaring variables inside an if or for loop doesn't limit them to that if or for block.)

I would not create inline onclick handlers like that. I'd probably do something more like this:

$('#adminPanel>ul>li').append("<a href='' data-cstmr='"+cstmr+"' class='lst_admin basic'>"+cstmr+"</a>");

...and then within the document ready setup a delegated event handler to catch the clicks on those anchors:

$('#adminPanel>ul>li').on('click', 'a.lst_admin', function() {
    $.ajax({
        type:'GET', url:'newsfpref.php?', data:'cref='+ $(this).attr('data-cstmr'),
        success:function(npfdata) {
            var item,
                n=0,
                // cache the jQuery object rather than reselecting on every iteration
                $table = $('#adminMain>table>tbody'); 
            // increment n only after the current iteration of the loop               
            for( ;item=npfdata[n]; n++) {
                // change to use item
                $table.append("<tr><td>"+item.nsource+"</td></tr>");
            }
         },
         dataType:'json'
    });
});

As you append your like with <a href='' onclick='getCustomerNP("+cstmr+")' , Make sure you can access the function getCustomerNP . Try to define getCustomerNP as

window.getCustomerNP = function(cstmrid) {
    ...

If you defined it in the $(document).ready(function(){ ... }) block, try this

    $('document').ready(function () {
        $.ajax({
            type: 'GET', url: 'cust_selection.php', data: '',
            succes: function (cstmrid) {
                var clistlen = cstmrid.length;
                var i = 0;
                var cstmr;
                for (; cstmr = cstmrid[i++]; ) {
                    var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
                        getCustomerNP(cstmr)
                    })
                    $('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
                }
            },
            dataType: 'json'
        });

        function getCustomerNP(cstmrid) {
            $.ajax({
                type: 'GET', url: 'newsfpref.php?', data: 'cref=' + cstmrid,
                success: function (nprfdata) {
                    var item;
                    var n = 0;
                    for (; item = npfdata[n++]; ) {
                        var news = npfdata[n].nsource;
                        $('#adminMain>table>tbody').append("<tr><td>" + item + "</td></tr>");
                    }
                },
                dataType: 'json'
            });
        }
    });

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