ajax.asyncget,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);

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值