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

时间:2018-03-03 03:16:43

标签: javascript ajax mongodb xmlhttprequest

我在mongodb中有两个表。

  1. GstState
  2. 存储
  3. 在我的Store表单中,我尝试通过进行ajax调用(用于获取GstStates)来选择基于国家/地区的状态,但我在JSON中获得idundefined 。我无法找到那个渔获物。

    这是我的代码:

    任何帮助都将不胜感激。

    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>
    

1 个答案:

答案 0 :(得分:0)

JavaScript很好。

idundefined的两个原因:

  1. JSON响应为空(您的服务器端代码从表中返回0行并将其发送回客户端)
  2. id属性不存在(检查区分大小写。也许您打算放Id?)
  3. 要调试此功能,请转到浏览器的开发人员工具 - &gt;网络即可。然后,通过正常触发事件进行监视,并调查所产生的AJAX调用的响应。