我的代碼有一個奇怪的問題,我似乎無法弄清楚。我對js比較陌生,利用http請求來檢索json數據,但是我已經能夠想出大部分可用的代碼。形式onsubmit和javascript的奇怪問題xmlhttprequest
本質上的工作流程如下:我有一個用戶輸入一些表單字段值,並選擇提交按鈕。 Onsubmit the apiCall()
函數被調用,然後調用createXMLHttpRequestObject()
和constructApiURL(searchtype)
函數創建,填充並通過代理髮送xmlHttpRequest
對象到搜索api url。一旦返回結果,將調用handleResults()
函數,然後使用函數handleResultsContainer()
解析結果並將其顯示在適當的div
容器中。
當我通過螢火蟲遍歷代碼時,一切正常。該對象被創建,通過代理髮送到搜索api,結果被返回並顯示,但是一旦焦點返回到功能onsubmit(event) {callApi();}
並且內容清除!?!我不知道該頁面是否重新加載或其他事情正在進行。
現在,如果我改變從表單提交到按鈕onclick的初始觸發器沒有問題的作品。用戶選擇該按鈕,搜索並顯示搜索結果,直到用戶再次選擇該按鈕,在該點清除結果並顯示新結果。問題是我必須對通常從窗體獲得的參數進行硬編碼。
有沒有人遇到過這個問題,或者看到了瀏覽器正在讀取的代碼如何導致這種情況?我的僞代碼如下。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function createXMLHttpRequestObject() {
-- code to create the XMLHttpRequestObject based on browser type --
}
function constructApiURL(searchtype) {
-- code to create the api url using the form values & proxy url --
}
function handleResultsContainer() {
-- code to create/remove search results display div
}
function handleResults(jsndata) {
-- code to parse and display results here --
}
function callApi() {
-- code to create XMLHttpRequestObject, populate it, and send it --
}
</script>
</head>
<body>
<form id="basicform" name="mashsearch" onsubmit="callApi()">
-- Code for user input fields which are then used by constructApiURL --
<input type="submit" id="searchbtn" value="Search!"/>
</form>
//Div displaying a Search Results Loading… message which is hidden/displayed//
<div id='loadingDiv' style="display:none">Search Results Loading...</div>
//Div used to display the search results
<div id='json'></div>
</body>
</html>
您還沒有在您的提交處理程序中添加'; return false;'或'event.preventDefault()'的符號。 – 2012-01-27 15:03:25
Doh!這工作謝謝! – frostedpops 2012-01-27 16:02:21