这段代码出了什么问题?

时间:2011-07-13 08:25:02

标签: javascript jquery debugging

这段代码有什么问题?我正在使用jQuery。

function setPreviewUrl() {
        $post_title = $("#post_title").val();
        $post_content = $("#post_content").val();
        $.get('ajax/base64encode.php?name='+post_title, function(data1) {
            var $postTitle  =   null;
            $postTitle  =   data1;
        });
        $.get('ajax/base64encode.php?name='+post_content, function(data2) {
            var $postCont   =   null;
            $postCont   =   data2;
        });
        var $urlExten   =   null;
        $urlExten   =   '?post_title='+postTitle+'&post_cont='+postCont;
        $("a[href*='#change']").attr('href', '<?php echo $site_url; ?>admin/ajax/preview.php'+urlExten);
        $("#preview_frame").prop("href", '<?php echo $site_url; ?>admin/ajax/preview.php'+urlExten);
    }

1 个答案:

答案 0 :(得分:1)

好像你搞乱了异步代码:

function setPreviewUrl() {
        var $post_title = null; 
        $post_title = $("#post_title").val();
        var $post_content = null; 
        $post_content = $("#post_content").val();
        $.get('ajax/base64encode.php?name='+post_title, function(data1) {
            var $postTitle  =   null;
            $postTitle  =   data1;
        });
        $.get('ajax/base64encode.php?name='+post_content, function(data2) {
            var $postCont   =   null;
            $postCont   =   data2;
        });
        // Those functions above will execute when the get is done, in the
        // meantime the code below is executed, so the variables have not been
        // set yet.
        // Also, the variables are only declared inside the get function so they
        // are not accessible due to their scope.
        var $urlExten   =   null;
        $urlExten   =   '?post_title='+postTitle+'&post_cont='+postCont;
        $("a[href*='#change']").attr('href', '<?php echo $site_url; ?>admin/ajax/preview.php'+urlExten);
        $("#preview_frame").prop("href", '<?php echo $site_url; ?>admin/ajax/preview.php'+urlExten);
    }