两个函数(Javascript和AJAX)不能协同工作

时间:2022-08-25 18:43:33

Im trying to send some data to the server through AJAX with the value i get from a JS variable. Code:

我试图通过AJAX向服务器发送一些数据,其中包含一个JS变量的值。代码:

<script type="text/javascript">
    var url;
    function aplicarFoto(_src) {
        url = _src;
        var fotosel = document.getElementById("fotosel");
        fotosel.src = 'fotos/'+_src;
    }

    function guardarCambios() {
        $.post("guardarCambios.php",
              {url: url},
              function(response) {
                  alert(response);
                  if (response == "NoUsuario") {
                      window.location = "../login.php";
                  } else {
                      alert("correcto");
                  }                         
              }
          alert(url);
    }
</script>

The idea is update the user picture with the url i get from aplicarFoto(_src) with the variable url . The first function (aplicarFoto(_src)) alone works correctly, but when i put the another function (guardarCambios()), the first function doesnt work, therefore the second neither! I dont know why, but it just happens when using ajax functions because i did a test with an alert(url) (sunrrounding the rest of code with comments) in the second function and both work correctly! Some guess? Thank you!

这个想法是用变量url从aplicarFoto(_src)中获取的url更新用户图片。第一个函数(aplicarFoto(_src))单独工作是正确的,但是当我放置另一个函数(guardarCambios())时,第一个函数不起作用,因此第二个函数也不起作用!我不知道为什么,但是在使用ajax函数时就会发生这种情况,因为我在第二个函数中使用了一个alert(url)(用注释覆盖其余的代码),这两个函数都可以正常工作!一些猜吗?谢谢你!

1 个解决方案

#1


3  

Your script alone has syntax errors.

您的脚本本身就有语法错误。

<script type="text/javascript">
var url;

function aplicarFoto(_src) {
    url = _src;
    var fotosel = document.getElementById("fotosel");
    fotosel.src = 'fotos/' + _src;

}

function guardarCambios() {
    $.post("guardarCambios.php", {
            url: url
        }, function (response) {
            alert(response);
            if (response == "NoUsuario") {
                window.location = "../login.php";

            } else {
                alert("correcto");
            }
            alert(url);
        }

    );
}
</script>

#1


3  

Your script alone has syntax errors.

您的脚本本身就有语法错误。

<script type="text/javascript">
var url;

function aplicarFoto(_src) {
    url = _src;
    var fotosel = document.getElementById("fotosel");
    fotosel.src = 'fotos/' + _src;

}

function guardarCambios() {
    $.post("guardarCambios.php", {
            url: url
        }, function (response) {
            alert(response);
            if (response == "NoUsuario") {
                window.location = "../login.php";

            } else {
                alert("correcto");
            }
            alert(url);
        }

    );
}
</script>