【问题标题】:What is undefined id in AJAX callAJAX 调用中未定义的 id 是什么
【发布时间】:2018-03-03 03:16:42
【问题描述】:

我在 mongodb 中有两个表。

  1. GstState
  2. 商店

在我的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


    【解决方案1】:

    JavaScript 没问题。

    idundefined 的两个原因:

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

    要对此进行调试,请转至浏览器的开发者工具 -> 网络。然后,通过正常触发事件进行监控,并调查产生的 AJAX 调用的响应。

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      相关资源
      最近更新 更多