简体   繁体   中英

Calling a user defined jQuery function

I'm a javascript newbie and I'm trying to call a jQuery function in this way:

function getProducts(){
      $.post("products.php",
      {
        customer_ID:$("#customers").val()
      },
      function(data,status){
        return status && data !== "";
      });
};

$(document).ready(function(){
    $("#customers").change(function(){
        if(getProducts){
            alert("trovato");

            $("#products").prop("disabled", false);
            $("#products").html(data);
        }else{
            alert("non trovato");

            $("#products").empty();
            $("#products").prop("disabled", true);
        }
    });
});

The if-else statement in the ready doesn't work although the function getProducts works properly. The problem, I suppose, is in the function call. What am I wrong with this? Thank you.

You need to wrap the response with a callback, like so:

function getProducts(callback){
      $.post("products.php",
      {
        customer_ID:$("#customers").val()
      },
      function(data,status){
         callback(status && data !== "");
      });
};

$(document).ready(function(){
    $("#customers").change(function(){
        getProducts(function(status) {
           if(status){
             alert("trovato");

             $("#products").prop("disabled", false);
             $("#products").html(data);
           }else{
             alert("non trovato");

             $("#products").empty();
             $("#products").prop("disabled", true);
           }
        });

    });
});

I'm not quite sure if this will work because of the asynchronized call inside of the function.

The obvious mistake is that you have to call a function like that: function() . You just forgot the parentheses.

If it won't work after that fix, you have to rework your program to use callbacks where you have asynchron calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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