使用jQuery$.post()通过函数返回值

Returning value via function with jQuery $.post()

本文关键字:函数 返回值 jQuery post 使用      更新时间:2023-09-26

我正试图存储用$.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。这个问题有道理吗?

您需要使用回调函数。

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);
   });
}

您正在调用一个异步函数。。

对你的功能进行一个小的修改就能解决这个问题:

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);
});
  • 它使用给定的url和post数据进行AJAX请求
  • 当它完成时,将调用done(),它将在自己内部调用回调