Return $.get data in a function using jQuery

前端 未结 6 1346
臣服心动
臣服心动 2020-11-29 20:29

I\'m trying to call a function that contains jQuery code. I want this function to return the results of the jQuery statement. It is not working, and I\'m trying to figure ou

6条回答
  •  孤街浪徒
    2020-11-29 21:15

    The fundamental mistake you are making is that the AJAX call is made asynchronously, so by the time you return, the result is not yet ready. To make this work you could modify your code like this:

    $(function() {
        showGetResult('John');
    });
    
    function showGetResult (name) {
        $.get('somefile.php', { 
            // Pass the name parameter in the data hash so that it gets properly
            // url encoded instead of concatenating it to the url.
            name: name 
        }, function(data) { 
            alert(data); 
        });
    }
    

提交回复
热议问题