【发布时间】:2018-03-03 03:16:42
【问题描述】:
我在 mongodb 中有两个表。
- GstState
- 商店
在我的Store 表单中,我试图通过进行 ajax 调用(用于获取 GstStates)来根据国家/地区选择州,但我在 JSON 中将id 获取为undefined。我无法找到那个捕获。
这是我的代码:
任何帮助将不胜感激。
JavaScript:
var countryHandle = document.querySelector('#store_country');
var stateHandle = document.querySelector('#store_gst_state_id');
countryHandle.addEventListener('change', function() {
if (countryHandle.value !== "") {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:3000/merchant_stores/find_states?
country = ' + countryHandle.value);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var states = JSON.parse(xhr.responseText);
var states1 = states.sort((a, b) =>
a.state_name.localeCompare(b.state_name))
stateHandle.innerHTML = "";
states1.forEach(function(state) {
var option = document.createElement('option');
var statename = document.createAttribute('value');
statename.value = state.id;
option.setAttributeNode(statename);
var namewithcode = state.state_name.concat(" - ", state.state_code)
var txt = document.createTextNode(namewithcode);
option.appendChild(txt);
stateHandle.appendChild(option);
});
}
}
xhr.send();
}
}, false)
HTML:
<div class="form-group">
<%= f.label :state, "State *", :class => "col-sm-2 control-label" %>
<%= f.collection_select :gst_state_id, [], :id, :state_name %>
</div>
<div class="form-group">
<%= f.label :country, "Country *", :class => "col-sm-2 control-label"
%>
<div class="col-md-10">
<%= f.select :country, options_for_select(Store::COUNTRY_CODES,
selected: @store.country),{}, class: "form-control" %>
</div>
【问题讨论】:
标签: javascript ajax mongodb xmlhttprequest