存储从ajax post返回的数据 - 我应该使用async:false来存储在var中吗?有没有更好的办法?

时间:2010-12-02 12:42:02

标签: jquery ajax

我有这段代码:

  $.post('http://localhost/test_zone/index.php/blog/new_post', { image_codes: images, info: fieldData, post_body: body },
    function(data){
     if (data.success) {
      if(data.error != ''){
        alert(data.error);
           }
      else {
        $('#preview_wrapper').css('display','none').html(data.postHTML).show(1000);
        $('#array_store').html(data.dataArray);
        }
      }
     else {
       alert('Sorry, an error occurred. No response from server.');
        }
       }

   ,'json');

正如你所看到的,我正在抓取两位数据 - postHTML& dataArray-通过ajax post函数。我想将dataArray放在var中。我已经阅读了类似的问题,我相信解决方案是使用'async:false' - 导致函数等待数据,并在继续之前将其插入var中。所以我有几个问题围绕着这个问题:

  1. 首先,如何使用简写的jquery $ .post设置'async:false',而不是$ .ajax({type:'POST'})?可能吗?这对我们来说很有用,但我无法解决或在任何地方找到答案。

  2. 我听过很多关于使用'async:false'的负面评论。你会推荐吗?如果没有,我怎样才能在页面上存储一些数据字符串供以后使用?目前您可以看到我已将数据设置为插入div(设置为display:none),这让我觉得不太理想,至少可以说。

  3. 为什么函数不等待数据插入到var中,但是当你将它设置为通过.html()将数据插入到页面上的元素时,它有效吗?我想这就像为数据字符串打开一扇门,只是在它自己的时间内溢出到页面中。?但是为什么这种方法不适用于将数据插入var-为什么门也不能对var保持开放? (如果你明白我的意思!)。

  4. 对一个相当冗长的问题抱歉 - 对上述各点的任何答案或部分答案都将非常感激。感谢。

    编辑:这是我的完整代码(您可以忽略所有数据收集位,但无论如何我都会发布) -

                    $('#submit').click(function(){
                        $('#input_table').hide(1000);
                        if($('.image_info').length){
                            var images = [];
                            $.each($('.image_info'), function(img_count) {
                                var img_code = $(this).attr('class').split(' ').slice(-1);
                                images.push('"' + img_count + '"' + ':' + '"' + img_code + '"');
                                img_count++;
                            });
                        images = '{' + images + '}';
                        }else {
                            var images = 'none';
                        }
                        var editor = CKEDITOR.instances.editor1;
                        var body = editor.getData();
                        body = clean(body);
                        var fieldData = [];
                        var cleanValue ='';                     
                        $.each($('.field'), function() {
                            cleanValue = clean($(this).val());
                            fieldData.push('"' + $(this).attr('id') + '"' + ':' + '"' + cleanValue + '"');
                        });
                        fieldData = '{' + fieldData + '}';
                        $.post('http://localhost/test_zone/index.php/blog/new_post', { image_codes: images, info: fieldData, post_body: body },
                                function(data){
                                    if (data.success) {
                                        if(data.error != ''){
                                                alert(data.error);
                                                            }
                                        else {
                                                $('#preview_wrapper').css('display','none').html(data.postHTML).show(1000);
                                                $('#array_store').html(data.dataArray);
                                             }
                                        }
                                    else {
                                            alert('Sorry, an error occurred. No response from server.');
                                          }
                                            }
    
                            ,'json');
                        });     
    

2 个答案:

答案 0 :(得分:0)

您不应该使用异步,因为您的浏览器会挂起。 我用事件完成了这个:

var evObj;
var _EVENT_RESULT = "resultEvent";

// Listen to the event
evObj.bind(_EVENT_RESULT, function(event, data){
  alert(data);
}

// Ajax-Request with event-triggering
$.ajax({
    type:       "POST",
    ...
    success:    function(data){
                  evObj.trigger(_EVENT_RESULT, data);
                }
});

该函数没有等待,因为它是异步的。这很好,因为您的代码不会停止,您的浏览器也不会挂起。 如果使用“.html()”,则将结果插入到页面中,如果结果是从服务器发回的。可能是,你只是在“思考”这是有效的,因为结果很快就会被发送回来。但是如果你的服务器会在10秒后发回结果,那么你的页面就不会有10秒的结果 - 但是:你gui不会挂起。

编辑:试试这个:

var evObj;
var _EVENT_RESULT = "resultEvent";

// Listen to the event
evObj.bind(_EVENT_RESULT, function(event, data){
  alert(data);
}

$('#submit').click(function(){
  ...
  else{
    ...
    $.post('http://localhost/test_zone/index.php/blog/new_post', {
      image_codes: images,
      info: fieldData,
      post_body: body },
      function(data){
        if (data.success){
          // At this point you could trigger the event
          evObj.trigger(_EVENT_RESULT, data);
        }
        else{
          alert('Sorry, an error occurred. No response from server.');
        }
        ,'json');
});

答案 1 :(得分:0)

设置你的vars:

  $.post('your_url', your_params,
     function(data){
       //Validation code here...
       window.postHTML = data.postHTML;
       window.dataArray = data.dataArray;     
  },'json');

现在您可以访问window.postHTMLwindow.dataArray全局变量。 要使$ .post同步(我不推荐),您只需使用$.ajaxSetup一次:

$.ajaxSetup({  //This will change behavior of all subsequent ajax requests!!
  async: false
});
$.post('http://localhost/test_zone/index.ph...) //Do $.post as usual

希望这有帮助

相关问题