开发者

jquery, response from the POST method

开发者 https://www.devze.com 2023-04-04 20:25 出处:网络
I get a response from the POST method. Inside I see the value, but after the POST method returns an empty value.

I get a response from the POST method. Inside I see the value, but after the POST method returns an empty value. Why, hot fix this?

sample:

$.post('/news/add/', {parent: name, title: 'none'}, function(data){ 
 new_id = dat开发者_Python百科a;
 alert(new_id); //11
});
alert(new_id); //empty


Because you are making an asynchronous call the code is run in this order:

1 - $.post('/news/add/', {parent: name, title: 'none'}, function(data){ 
   3 - new_id = data;
   4 - alert(new_id); //11
});
2 - alert(new_id); //empty

You can only use the value returned by your post inside the callback function.

The only other way to do this is to make the request synchronous. But that's really not advised as it can lock out the browser waiting for the response.


You maybe want to use the .complete or .success methods: http://api.jquery.com/jQuery.post/#jqxhr-object

0

精彩评论

暂无评论...
验证码 换一张
取 消