jquery $.get & $.ajax , abour async & sync

You have a few different mistakes. First, $.get doesn't return the return value of the callback function. It returns the XHR object. Second, the get function isn't synchronous, it's asynchronous so showGetResult will likely return before get completes. Third, you can't return something from inside the callback to the outer scope. You can, however, bind a variable in the outer scope and set it in the callback. To get the functionality that you want, you'll need to use $.ajax and set the async option to false. Then you can define a variable in the outer scope and assign it in the ajax callback, returning this variable from the function.
function showGetResult( name ){ 
var result = null; var scriptUrl = "somefile.php?name=" + name; 
$.ajax({ url: scriptUrl, type: 'get', dataType: 'html', async: false, success: function(data) { result = data; } }); 
return result;}

You would probably be better served, though, figuring out how to do what you want in the callback function itself rather than changing from asynchronous to synchronous calls.
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); 
    });
}

좋은 웹페이지 즐겨찾기