开发者

Why Doesn't my ajax,javascript work?

I'm writing a website to search through my python database. The nonjavascript version worked perfectly. But now I want to use ajax so that the page doesn't have to be refreshed. I.e., the results will show up as soon as the search button is clicked. But it don't work (I click the button and nothing happens). Why not???

<script language="javascript">
var xmlhttp;
   if (window.XMLHttpRequest)
     {// code for IE7+, Firefox, Chrome, Opera, Safari
     xmlhttp=new XMLHttpRequest();}
   else
     {// co开发者_开发问答de 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>


Well the problem is that this is considered a cross domain request and your browser natively blocks such responses. You need to use jsonp for the same.

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

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

you can get an example of your exact problem here: http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON (search for Same Origin Policy on the page)

in essence this is what you want:

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);


You may need to return false inside your event handler to prevent the default from executing.


I got it to work by changing two things:

1)I changed xmlhttp.responseXML to xmlhttp.responseTEXT even though my fetched file is written in HTML. Shouldn't it be XML and not TEXT then?

2) the target element was a <div>. I changed the target element to a <p> and it worked. Does innerHTML not work in <div>?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜