如何使用$ .get()中的变量 [英] How to use a variable from $.get()

查看:173
本文介绍了如何使用$ .get()中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看一下$ .get().我需要在后续的$ .post()中使用变量nextId,但是存在在$ .get()范围之外无法定义的问题

Kindly take a look at $.get(). I need to use the variable nextId in the subsequent $.post() but having the problem of being undefined outside the scope of $.get()

$('#addbtn').click(function(){

    var insname = $('#ins').val();
    var itemexist = false;

    $.each($('#selname option'), function(key, value){
        if($(this).text() == $.trim(insname)){
            itemexist = true;
            alert("Item already exists: "+$(this).text());
        }
    });

    if(insname=='') alert("Cannot be empty");

    if(!itemexist && insname!='') {

        $.get('data1.php',

            function(retId){
                var nextId = retId;
                var incrementlength = 1;
                incrementlength+= $('#selname option').length;

                $('#selname').attr('size',incrementlength);
                $('#selname')
                    .append($('<option></option>')
                    .attr('value', nextId).text(insname));
                $('#ins').val('');
            });

        alert(nextId);//nextId is not defined
        $.post('data1_1.php', {id: nextId, name: insname},);
    }
});

谢谢

推荐答案

此处发生的是nextId是在异步回调期间设置的,因此在调用警报时,nextId是未定义的,因为它没有尚未设定.如果要在$.post()中使用返回的nextId,则必须在$.get()回调完成后调用$.post().如下修改您的代码,它应该可以工作:

What happens here is that the nextId is set during an asynchronous callback, so when you are calling the alert, nextId is undefined, because it hasn't been set yet. If you want to use the returned nextId in the $.post() you will have to call the $.post() after the $.get() callback completes. Modify your code as below and it should work:

尝试一下:

$('#addbtn').click(function(){

    var insname = $('#ins').val();
    var itemexist = false;

    $.each($('#selname option'), function(key, value){

        if($(this).text() == $.trim(insname)){
            itemexist = true;
            alert("Item already exists: "+$(this).text());
        }
        });

        if(insname=='') alert("Cannot be empty");
        if(!itemexist && insname!=''){
        $.get('data1.php',
                function(retId){
                    var nextId = retId;
            var incrementlength = 1;
            incrementlength+= $('#selname option').length;
            $('#selname').attr('size',incrementlength);
            $('#selname').append($('<option></option>').attr('value', nextId).text(insname));
            $('#ins').val('');
            alert(nextId);//nextId should be defined
            $.post('data1_1.php',
                    {id: nextId, name: insname},
                    );
            }
        });


});

这篇关于如何使用$ .get()中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆