2011-08-20 67 views
1

我在寫一個網站來搜索我的python數據庫。非JavaScript版本完美運行。但是現在我想使用ajax,因此不必刷新頁面。即,一旦搜索按鈕被點擊,結果就會顯示出來。但它不起作用(我點擊按鈕,沒有任何反應)。爲什麼不???爲什麼我的ajax,javascript工作?

<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> 
+1

運行與螢火頁啓用(插件)與Firefox和張貼任何錯誤,當您按下 – Ben

+0

您可能需要在事件處理中 – secretformula

+0

感謝 我嘗試螢火而事實證明,沒有錯誤時返回false按鈕,它顯示。我試圖切換到假,但那也沒有工作 – Kbob

回答

1

您可能需要在事件處理程序中返回false以防止默認執行​​。

+0

謝謝,改爲false雖然不起作用,但 – Kbob

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

爲什麼如果請求來自localhost,他還需要使用JSONP嗎?我假設他正在運行本地測試服務器 – secretformula

+0

它無關緊要,如果你是在不同的端口或子域進行通信,無論瀏覽器不允許你在哪裏......這裏http://en.wikipedia.org/wiki/Same_origin_policy# Origin_determination_rules – Baz1nga

+0

沒有注意到不同的端口部分,我的壞 – secretformula

0

我通過改變兩件事情來實現它:

1)我將xmlhttp.responseXML更改爲xmlhttp.responseTEXT,即使我提取的文件是用HTML編寫的。它不應該是XML而不是TEXT嗎?

2)目標元素是<div>。我將目標元素更改爲<p>,它工作。 innerHTML在<div>中不起作用嗎?

相關問題