AJAX调用中未定义的id是什么

问题描述 投票:0回答:1

我在mongodb有两张桌子。

  1. GstState
  2. 商店

在我的Store形式中,我试图通过进行ajax调用(用于获取GstStates)来选择基于国家的状态,但是我在QSON中将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
1个回答
0
投票

JavaScript很好。

id的两个原因是undefined

  1. JSON响应为空(您的服务器端代码从表中返回0行并将其发送回客户端)
  2. id属性不存在(检查区分大小写。也许你打算把Id?)

要调试它,请转到浏览器的开发人员工具 - >网络。然后,通过正常触发事件进行监视,并调查所产生的AJAX调用的响应。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.