【问题标题】:Why Doesn't my ajax,javascript work?为什么我的 ajax、javascript 不起作用?
【发布时间】:2011-10-31 02:38:54
【问题描述】:

我正在编写一个网站来搜索我的 python 数据库。非javascript版本完美运行。但现在我想使用 ajax 以便不必刷新页面。即,一旦单击搜索按钮,结果就会显示出来。但它不起作用(我点击按钮,没有任何反应)。为什么不???

<script language="javascript">
var xmlhttp;
   if (window.XMLHttpRequest)
     {// code for IE7+, Firefox, Chrome, Opera, Safari
     xmlhttp=new XMLHttpRequest();}
   else
     {// code for IE6, IE5
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

function getData(){
if(xmlhttp) {
var obj = document.getElementById("search-results");
xmlhttp.open("GET","http://127.0.0.1:8000/search/?name=i&city=o",true);
xmlhttp.onreadystatechange = function()  {
    if (xmlhttp.readyState == 4 &&
    xmlhttp.status == 200) {
    obj.innerHTML = xmlhttp.responseXML;
    }}
xmlhttp.send(null);
  }}
</script>
</head><body>
<form id="search-form" action="" method="get">
    <input type="text" name="name" id="name">
    <input type="text" name="city" id="city">
    <input type="button" value="Search" onclick = "getData()">
</form>     
<div id="search-results"></div></body>

【问题讨论】:

  • 使用 firefox 运行启用了 firebug 的页面(一个插件),并发布按下按钮时显示的任何错误
  • 您可能需要在事件处理程序中返回 false
  • 感谢我尝试了 firebug,它没有显示任何错误。我尝试切换到 false,但这也没有用
  • @secretformula - 我很确定这会解决它。我会将其发布为答案。

标签: javascript ajax forms search


【解决方案1】:

您可能需要在事件处理程序中返回 false 以防止执行默认值。

【讨论】:

    【解决方案2】:

    我通过改变两件事让它工作:

    1)我将 xmlhttp.responseXML 更改为 xmlhttp.responseTEXT,即使我获取的文件是用 HTML 编写的。那不应该是 XML 而不是 TEXT 吗?

    2) 目标元素是&lt;div&gt;。我将目标元素更改为&lt;p&gt;,它起作用了。 innerHTML 在&lt;div&gt; 中不起作用吗?

    【讨论】:

      【解决方案3】:

      问题在于这被认为是跨域请求,而您的浏览器本身会阻止此类响应。你需要使用 jsonp 来做同样的事情。

      http://remysharp.com/2007/10/08/what-is-jsonp/

      http://code.google.com/p/jquery-jsonp/

      您可以在此处获得确切问题的示例:http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON(在页面上搜索同源策略)

      本质上这就是你想要的:

      var url = "http://127.0.0.1:8000/search/?name=i&city=ocallback=jsonCallback";
      
      var script = document.createElement("script");
        script.setAttribute("src", url);
        script.setAttribute("type", "text/javascript");
      
        window.jsonCallback = function(jsonObj) {
      
        document.body.removeChild(script);
        delete window[callback];
      }
      
      document.body.appendChild(script);
      

      【讨论】:

      • 如果请求也来自本地主机,为什么他需要使用 JSONP?我假设他正在运行本地测试服务器
      • 无论您是在不同的端口或子域上进行通信,浏览器都不允许您这样做,都没有关系.. 这里en.wikipedia.org/wiki/…
      • 没有注意到不同的端口部分,我的错
      猜你喜欢
      • 2012-01-07
      • 2011-09-18
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 2023-03-31
      相关资源
      最近更新 更多