简体   繁体   English

调用javascript函数,值在控制台中返回为undefined

[英]Calling a javascript function, value returns as undefined in the console

So I have a city dropdown which is populated by an onchange, I am trying to get it so that it doesn't require the onchange every time the page reloads, since it is a form. 所以我有一个城市下拉列表,由onchange填充,我试图得到它,以便每次页面重新加载时都不需要onchange,因为它是一个表单。

this is the states dropdown, which works. 这是状态下拉,这是有效的。

<p id=stateDiv><label>State</label></p><p><select name='States' id='States'  onchange='getCity(this.value)'>
            " . $states . "
        </select></p>";

this is the city drop down function call which does not work. 这是城市下拉功能调用,它不起作用。 I am new to javascript, so I am not sure about how to format a call with php. 我是javascript的新手,所以我不确定如何使用php格式化调用。

if($state==""){   
echo '<p id="citydiv"></p>';
}else{
    echo '<p id="citydiv"><script type="text/javascript">getCity('.$state.');</script></p>';
}

getCity function getCity函数

function getCity(stateId)
{
  var strURL="findcity.php?state="+stateId;
  var req = getXMLHTTP();
 if (req)
 {
  req.onreadystatechange = function()
  {
    if (req.readyState == 4) // only if "OK"
    {
      if (req.status == 200)
      {
        document.getElementById('citydiv').innerHTML=req.responseText;
       } else {
         alert("There was a problem while using XMLHTTP:\n" + req.statusText);
       }
    }
   }
   req.open("GET", strURL, true);
   req.send(null);
 }
}

When you get problems like this, ALWAYS look at the HTML source. 当您遇到这样的问题时,请始终查看HTML源代码。 In this case you might see: 在这种情况下,您可能会看到:

getCity(GA);

Clearly this is wrong, that should be "GA" . 显然这是错误的,应该是"GA"

Whenever you dump a PHP variable into JavaScript, always use json_encode . 无论何时将PHP变量转储到JavaScript中,都要使用json_encode

Along with what Kolink said, what does your javascript function "getCity" look like? 与Kolink所说的一样,你的javascript函数“getCity”是什么样的? If it is just returning a value, this will not work. 如果它只是返回一个值,这将不起作用。 You will either need to grab the element ( document.getElementById('cityDiv') ) and set the innerHTML to the return value OR use document.write instead of returning a value. 您将需要获取元素( document.getElementById('cityDiv') )并将innerHTML设置为返回值或使用document.write而不是返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM