如何将 jQuery.post 数据存储到局部变量,以便我可以使用它


how can i store data from jQuery.post to a local variable so that i can work with it?

this.formsValidation = function(form_id)
{
    var fieldNames;
    jQuery.post('index.php','option=com_itcs_forms&controller=itcs_fields&task=getFieldsNameForValidation&tmpl=component&form_id='+form_id,
    function(data)
    {
        fieldNames = data;
    });
    alert(fieldNames);
    return false;
}

这里的"fieldNames"显示"未定义",尽管它必须显示"data"中的字符串。我无法将"数据"存储到变量中,以便我可以在"发布"功能之后使用它。怎么办呢?

执行以下操作 -

this.formsValidation = function(form_id)
{
    var fieldNames;
    jQuery.post('index.php','option=com_itcs_forms&controller=itcs_fields&task=getFieldsNameForValidation&tmpl=component&form_id='+form_id, 
     function(data)
     {
         fieldNames = data;
         alert(fieldNames);
     });
     return false;
}

你的赋值应该有效,但你的代码是异步执行的 - 也就是说,你正在发出 AJAX 调用,然后在 AJAX 调用完成之前立即执行alert()。如果您希望使用数据,则应在 AJAX 回调中执行此操作,从而保证在执行代码时拥有数据:

var fieldNames;
jQuery.post('index.php','option=com_itcs_forms&controller=itcs_fields&task=getFieldsNameForValidation&tmpl=component&form_id='+form_id,
function(data)
  {
     fieldNames = data;
     alert(fieldNames);
     // do more stuff here
  });
相关文章: