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

here "fieldNames" is showing "undefined" although it must show a string which is in "data". i am unable to store "data" to a variable, so that i can work with it after "post" function. how to do that?

4

2 回答 2

1

请执行下列操作 -

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;
}
于 2013-09-13T10:23:10.647 回答
0

您的分配应该可以工作,但是您的代码是异步执行的——也就是说,您正在发出 AJAX 调用,然后alert()在 AJAX 调用完成之前立即执行。如果您希望使用数据,您应该在 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

  });
于 2013-09-13T10:26:22.660 回答