2013-02-14 68 views
1

我想使用jQuery的ajax調用php腳本onload。該腳本將從url web服務返回xml,並通過它進行解析,然後在頁面加載(onload)時將它的位和片段顯示到div標記中。當我使用表單的時候,我對php很滿意,但是讓PHP腳本運行onload並不適合我。有人可以看看我的代碼,並給我你的建議嗎?提前致謝。jQuery調用php腳本onload

HTML:

<!doctype html> 
<html> 
    <head> 

    <title>Word of the Day</title> 

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
    <script src="code.js"></script> 

    </head> 
<body> 

<h3>Word of the Day: </h3> 
<div id="word_day"></div> 

</body> 
</html> 

的JavaScript:

$(document).ready(function() { 

    $(window).load(function() { 


    $.ajax({ 
     post: "GET", 
     url: "word_day.php" 
    }).done(function() { 
     alert(this.responseText); 
    }).fail(function() { 
     alert(this.responseText); 
    }); 


    }); 

}); 

我沒加我的PHP代碼,因爲我敢肯定,這是不是我的事業受挫。

+1

是完成或失敗的事件? – Taz 2013-02-14 01:08:47

+0

如果將「this.responseText」替換爲成功或失敗等字符串,但輸入「this.responseText」會產生未定義的內容,則會觸發「已完成」事件。 – JaPerk14 2013-02-14 01:10:53

+0

word_day.php存在於你的web根目錄下嗎? – kufudo 2013-02-14 01:12:01

回答

1

你並不需要這兩個處理程序,只有一個:

$(document).ready(function() 
{ 
    $.ajax(
    { 
     post: "GET", 
     url: "word_day.php" 
    }).done(function() 
    { 
     alert(this.responseText); 
    }).fail(function() 
    { 
     alert(this.responseText); 
    }); 

}); 

當你有它,你正試圖創建一個處理程序時的處理程序解僱這是從來沒有去上班。

編輯:

你做/失敗的部分應該是這樣的:被觸發

}).done(function(data) 
{ 
    alert(data); 
}).fail(function(jqXHR, textStatus, errorThrown) 
{ 
    alert(textStatus); 
}); 
+0

我試過這個,但我仍然沒有定義。我猜我不應該使用this.responseText。 – JaPerk14 2013-02-14 01:14:59

+0

是的,正確的。看到我的編輯... – 2013-02-14 01:15:58

+0

太棒了!有效。你能幫我理解爲什麼我必須添加這些參數才能使它工作嗎? – JaPerk14 2013-02-14 01:20:14