0

我正在尝试创建一个函数来通过 请求我们数据库中有关国家/地区 ID 的信息ajax,因为这就是address我查询的表中数据的表示方式。即在address表中,代表id的是国家而不是国家名称,而实际的国家名称在我查询的另一个表中。

发送ajax请求后,我创建了一个我得到的地址字符串。但是,它只更新对象的最后一个值,而不是全部。这是我的咖啡脚本:

requests = Array()
for key, val of {'Correspondence_Country__c':data['Correspondence_Country__c'], 'Country_of_Residence__c': data['Country_of_Residence__c']}
        console.log(key)
        console.log(val)
        requests.push($.ajax
                url: window.location.pathname
                type: 'post'
                dataType: 'json'
                data: 'search_id=' + val + '&search_column=Id&sobject=Country__c&columns=["Name"]'
                error: (jqXHR, textStatus, errorThrown) ->
                        alert('Error: ' + textStatus + ': ' + errorThrown)
                success: (c_data, textStatus, jqXHR) ->
                        data[key] = c_data['Name']
                        console.log(c_data['Name'])
                        console.log(key)
        )
defer = $.when.apply($, requests)

我省略了这个defer.done功能。console.log信息的结果如下:

China P.R. 
Country_of_Residence__c 
China P.R. 
Country_of_Residence__c

而不是预期的

China P.R. 
Correspondence_Country__c
China P.R. 
Country_of_Residence__c

我的 Coffeescript 有问题吗?

编辑:看起来这与ajax请求或将请求推ajax送到requests数组有关。console.log()在我推送调用之前,我在函数的开头添加了一对ajax,它产生了以下信息:

Correspondence_Country__c
a063000000CZoZHAA1
Country_of_Residence__c
a063000000CZoZHAA1 
4

1 回答 1

2

$.ajax是异步的(除非另有说明,但您不想这样做)。这意味着循环将在 ajax 调用完成之前结束。当那个 ajax 调用最终结束时,“key”将是数组的最后一个值。(JS 没有块作用域)。

使用咖啡do来保持正确的价值。

for key, val of {'Correspondence_Country__c':data['Correspondence_Country__c'], 'Country_of_Residence__c': data['Country_of_Residence__c']}
  do (key) ->
    # your code
于 2013-08-22T16:52:56.170 回答