简体   繁体   English

请求咨询-使用json / jquery和ajax在函数之间传递变量

[英]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). 我已经看过很多关于SO的“类似”问答线程,但是老实说,由于我对js编程没有太多的了解,所以我很难理解很多答案(只要它们适用于我自己的情况)。

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). 上下文是这样,我有两个php脚本,一个返回设定时间段的customer_ids列表(json编码),另一个返回他们对新闻提要的偏好(json编码)。

I wrote the following, having googled a bit to get a basic understanding of how to setup an ajax function in jQuery: 我写了下面的文章,在Google进行了一些搜索,以基本了解如何在jQuery中设置ajax函数:

$('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. 现在,从第一个ajax函数中,我将获得一个链接列表,我想要单击这些链接以启动第二个ajax函数并将其客户ID传递给它,以便它可以获取他们为其配置的新闻源的列表。他们的页面。 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: ... 警报和带有硬编码的客户ID均表明该功能正在“运行”,但是当我尝试调整第一个功能时,...

$('#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. 第二个函数似乎没有“接收”该变量,并且我不确定这是否是我忽略的基本内容(例如有些混淆的“和”展示位置),或者我要完成的实际上不是jQuery ajax函数相互交互的方式。

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. 正如您所看到的,我已经蚕食了许多SO Q&A线程中的一些代码和想法,但是在没有太多了解的情况下进行复制会导致令人沮丧的依赖生活。

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() . 您在getCustomerNP()中的$.ajax()成功函数中有错字。 The function declaration: 函数声明:

success:function(nprfdata) {

... has a parameter nprfdata , but then within the function you use npfdata (missing the r ). ...具有参数nprfdata ,但随后在函数中使用npfdata (缺少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. ...声明并设置您从未使用过的可变news And it doesn't seem right to increment n in the for test expression but then use n within the loop. 并且在for测试表达式中增加n似乎不正确,但是在循环中使用n You never set item to anything but you use it in your .append() . 您从来没有将item设置为任何东西,而是在.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.) (还要注意,JS没有块范围,只有函数范围,因此在if或for循环内声明变量不会将它们限制为if或for块。)

I would not create inline onclick handlers like that. 我不会像那样创建内联onclick处理程序。 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 . <a href='' onclick='getCustomerNP("+cstmr+")'附加喜欢<a href='' onclick='getCustomerNP("+cstmr+")' ,请确保可以访问函数getCustomerNP Try to define getCustomerNP as 尝试将getCustomerNP定义为

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

If you defined it in the $(document).ready(function(){ ... }) block, try this 如果您在$(document).ready(function(){ ... })块中定义了它,请尝试此操作

    $('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'
            });
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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