<!doctype html>
<html>
<head>
<title>Twitter</title>
<meta charset="utf-8">
<script>
window.onload = function() {
// set up the click handler for the form button
var button = document.getElementById("submit");
button.onclick = getTweets;
}
// when you click "Get Tweets" we call this function
function getTweets() {
// set up a new XHR request
var xhr = new XMLHttpRequest();
// we're calling search.php and passing in a query string
var url = "search.php?query=";
var query = document.getElementById("query").value;
if (!query) {
query = "html5";
}
// we encode the query to handle any special characters properly
url += encodeURIComponent(query);
// this is the function that is called when the XHR request
// to our search.php script is handled, and a response sent back
xhr.onload = function() {
// if everything went okay, then send the response data
// to the displayTweets() function
if (xhr.status == 200) {
displayTweets(xhr.responseText);
} else {
var errorDiv = document.getElementById("error");
errorDiv.innerHTML = "Error getting tweets: " + xhr.status;
}
};
// make the request!
xhr.open("GET", url);
xhr.send(null);
}
function displayTweets(tweets) {
// tweets is a big long string, so we need to parse it
// into JSON first
tweets = JSON.parse(tweets);
var ul = document.querySelector("ul");
// clear existing tweets from list
while (ul.hasChildNodes()) {
ul.removeChild(ul.lastChild);
}
// add new tweets
for (var i = 0; i < tweets.length; i++) {
var li = document.createElement("li");
li.innerHTML = tweets[i].tweet;
ul.appendChild(li);
}
}
</script>
</head>
<body>
<form>
Query:
<input type="text" id="query">
<input type="button" id="submit" value="Get Tweets">
</form>
<div id="error"></div>
<ul></ul>
</body>
</html>
鳴叫的提取在上面的代碼時,我在文字框中輸入一些文字,然後點擊「獲取鳴叫」按鈕,它提供了一個錯誤爲Error getting tweets: 0
。 search.php獨立執行而不嵌入html和javascript時會提供準確和所需的結果。您可以檢查html和js代碼並提示代碼中的任何更改嗎?錯誤從Twitter
有一種簡單的方法可以自己調試:在Chrome或Firefox中打開開發人員工具(F12)並打開「網絡」選項卡。在那裏你會看到HTTP請求到底是什麼以及響應是什麼。也許有一些ID丟失或類似的東西,你會得到服務器的500錯誤。 –
調試後發現它在search.php中發現「no element found」錯誤,我應該如何解決它? – user3219417
修改以下行作爲 如果(xhr.status == 200),如果(xhr.readyState == 4 && xhr.status == 200) 和 xhr.open( 「GET」,URL)來XHR .open(「GET」,url,true) – kcak11