-3

I have a question about $.ajax in javascript:

If I have a function like this:

var jQueryFunction = function()
{
   var array = new Array();       
   ...

   $.ajax ({
       type: "GET",
       async: false,
       url: TPS_URL_1,
       dataType: "jsonp",
       jsonp: "callback",
       jsonpCallback: "tpsHandler",
       success: function(json)
       {
          array[0] = 1;
          array[1] = 2;
       }
   });

}

After that when I check array value, it isn't set by anything and still null.

However I do like this:

var jQueryFunction = function()
{
   var array = new Array(); 
       array[0] = 1;
       array[1] = 2;      
   ...

   $.ajax ({
       ...

   });

}

It works fine.

So why I cannot set value for array inside $.ajax?

4

2 回答 2

1

该行$.ajax({...})相当于

var obj = {...};
$.ajax(obj);

该语句array[0] = 1不能放在这样的对象声明中(即代码var obj = {array[0]=1}无效),因此您发布的代码无效(它会引发 SyntaxError)

如果要在 ajax 返回后设置这些数组元素,则应使用成功回调:

$.ajax({url: ...,
    success: function(returnData) {
        array[0] = 1;
    }
});
于 2013-10-02T18:23:25.467 回答
-1

尝试:

简单的:

var setup = {
    url         :   'index.php',
    dataType    :   "json",
    type        :   "post",
    data        :   {
        time        :   "now"
    },
    success     :   function(response)
    {
        console.log( response ) ;
    }
};
$.ajax( setup );

API( ajaxSetup ):

$.ajaxSetup({
    url         :   'index.php',
    dataType    :   "json",
    type        :   "post",
    success     :   function(response)
    {
        console.log( response ) ;
    }
});

$.ajax({
    data:{
        time    :   "now"
    }
});
于 2013-10-02T18:31:48.000 回答