【发布时间】:2020-08-09 03:23:28
【问题描述】:
我正在尝试根据存储的(数组)值“填充”表单中的选择:city_selector_vars。这个存储的值显示了正确的值(见下面的代码)。
我遍历这个数组并尝试为定义的 stateCode 获取城市 (get_states)。我将 stateCode 作为值传递给函数。
如果我在$.post 之前登录state_data.country_code,我会得到预期的回报。如果我在$.post 中记录state_data.country_code,它并不总是与传递的国家代码相同。我认为这与范围有关,但我的知识不足以弄清楚。
/**
* city_selector_vars
* [
* 'countryCode' => 'NL',
* 'stateCode' => 'NL-FL',
* 'cityName' => 'A name'
* ]
* [
* 'countryCode' => 'BE',
* 'stateCode' => 'BE-BR',
* 'cityName' => 'Another name'
* ]
*/
if ( true === Array.isArray(city_selector_vars) ) {
for (i = 0; i < city_selector_vars.length; i++ ) {
get_states(city_selector_vars[i].countryCode, (response)=> {
// console.log(response);
});
}
}
function get_states(countryCode, callback) {
const state_data = {
action: 'get_states_call',
country_code: countryCode
};
// console.log(state_data.country_code) shows correct country code
$.post(ajaxurl, state_data, (response)=> {
// here the wrong response first shows
// state_data.country_code is not always the same as state_data.country_code
callback(response);
});
}
function get_states_call( $country_code = false ) {
// $country_code = always false, even though it is passed
if ( false == $country_code ) {
if ( isset( $_POST[ 'country_code' ] ) ) {
// here it sometimes picks up the incorrect value
$country_code = $_POST[ 'country_code' ];
}
}
// code removed, since depends on code above
$items = [];
echo json_encode( $items );
die();
}
因为它只是有时会拾取错误的值,我认为它与范围有关,但我没有足够的知识来确定它。
【问题讨论】:
-
那是因为 AJAX 是异步的。你不知道回调的执行顺序。
-
是的,但这并不能回答问题:) 你只是在陈述一个事实。
-
是的,我已经尝试过他的解决方案,但无法让它发挥作用,可能是因为我没有提供更多关于“内部”get_states 的信息。
-
我之前已经在 get_states 中添加了它作为参数,但据我所知,这似乎没有起到作用。
-
@mateleco 我刚刚更新了改编后的代码,并附有 muka.gergely 的一些指针。使用 async/await 我每次只得到 1 个结果。当我删除它(但保留他的其余代码)时,我得到了预期的结果。更新代码中的 console.log (可以找到 here 给了我预期的结果,但要使用它,我需要解析承诺值,这就是它现在再次弄乱订单的地方。
标签: javascript php jquery scope