我试图存储一个使用$.post()
获得的值,但我遇到了一个问题,在运行$.post()
之前正在设置变量。我还是不明白。$.post()
封装在通用重用方法中。下面的Javascript代码。
// call the post function
var zip_check = sendPost('{some url here}', new_zip);
console.log(zip_check);
/**
* sendPost
*
* Sends data via jQuery post and returns required result.
*
* @param string target_url - where post is going
* @param string post_data - information to be sent
* @return string - data to be manipulated
*/
function sendPost(target_url, post_data) {
$.post(target_url, {
post_data:post_data
}).done(function(data) {
console.log(data);
return data;
}).fail(function(e) {
console.log('AJAX Failure: ' + e);
});
}
如前所述,zip_check
将存储“未定义”,打印到控制台,然后$.post()
将运行,但不会将值返回给zip_check
。这个问题有意义吗?
发布于 2014-04-22 21:02:01
您需要使用回调函数。
sendPost('test.php', {zipcode:12345}, checkZipcode);
function checkZipcode(new_zip)
{
/** Do stuff with your zip code **/
console.log(new_zip);
}
/**
* sendPost
*
* Sends data via jQuery post and returns required result.
*
* @param string target_url - where post is going
* @param string post_data - information to be sent
* @param function callback - function called after POST response
*/
function sendPost(target_url, post_data, callback) {
$.post(target_url, {
post_data:post_data
}).done(function(data) {
console.log(data);
callback(data);
}).fail(function(e) {
console.log('AJAX Failure: ' + e);
});
}
发布于 2014-04-22 20:58:29
您正在调用一个异步函数。
对您的功能进行一次小小的修改就可以解决这个问题:
function sendPost(target_url, post_data, callback) {
$.post(target_url, {
post_data: post_data
}).done(callback).fail(function (e) {
console.log('AJAX Failure: ' + e);
});
}
sendPost('http://jsfiddle.net/echo/jsonp/ ', {
data: 'send'
}, function (data) {
console.log(data);
});
https://stackoverflow.com/questions/23229941
复制相似问题