为什么我的ajax,javascript不起作用?

时间:2011-08-20 06:51:13

标签: javascript ajax forms search

我正在写一个网站来搜索我的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>

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

问题是,这被视为跨域请求,您的浏览器本身会阻止此类响应。你需要使用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);

答案 2 :(得分:0)

我通过改变两件事来实现它:

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

2)目标元素是<div>。我将目标元素更改为<p>并且它有效。 innerHTML在<div>中不起作用吗?