繁体   English   中英

jQuery $ .post返回数据

[英]jQuery $.post returned data

我在如何使用jQuery的$ .post函数返回的数据方面遇到一些问题。 我正在尝试测试服务器上是否存在图片。

这是javascript:

$.post("ajax_test_file.php",
    {filename: filetocheck},
    function(data){
        if(data==1){
            var img_ref_up = 'value 1';
        }else{
            var img_ref_up = 'value 1';
        }
    }
);

[Following code trying to use img_ref_up's value]

这是ajax_test_file.php内容:

$filename = $_POST["filename"];

if (file_exists($filename)) {
    echo 1;
} else {
    echo 0;
}

我想要做的是在$ .post(...)之后使用img_ref_up的值

有人对此有任何线索吗? 提前致谢

$.post正在异步运行,因此您似乎在ajax请求完成之前正在访问该值。 您可以将代码移动到成功回调中,这可以确保在使用该变量之前设置image_ref_up的值。

$.post("ajax_test_file.php",
    {filename: filetocheck},
    function(data){
        if(data==1){
            var img_ref_up = 'value 1';
        }else{
            var img_ref_up = 'value 1';
        }
        // move your code here
    }
);

您不能/不应该-ajax调用是异步的(可以使其同步,但强烈建议不要这样做)。 您必须在回调方法中处理结果:

$.post("ajax_test_file.php",
    {filename: filetocheck},
    function(data){
        if(data==1){
            var img_ref_up = 'value 1';
        }else{
            var img_ref_up = 'value 1';
        }
        ///// DO WHATEVER YOU NEED HERE
        [Following code trying to use img_ref_up's value]
    }
);

由于请求是异步的,因此可能会在帖子完成之前执行[以下代码]部分。 你应该这样做。

$.post('url', function(data) {
    var img_ref_up;
    if (data == 1) {
        img_ref_up = 'value 1';
    }
    doSomethingWithRefUp(img_ref_up);
});

function doSomethingWithRefUp(img_ref_up) {
     [Following code]
}

暂无
暂无

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

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