2013-12-11 58 views
0

我創建了一個簡單的應用程序,它連接到一個REST API,如下所示:div標籤未更新

<!DOCTYPE html> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <script src="http://code.jquery.com/jquery-latest.min.js" > 
    </script> 
    <title></title> 
    </head> 
    <body> 
    <h1 id="header">A headline</h1> 
     <div id = "info"></div> 
     <p1 id = "p1">p1</p1> 
    <form id="name" name="name"> 
     Please enter a switch: <input type="text" name="switch" id = "switch"> 
     <input type="submit" value="submit" name="submit" id="submit"> 
    </form> 

    <script> 
     $(document).ready(function() { 
      $('#name').submit(function() { 
       alert('submitted'); 
       var switchName = $('#switch').val(); 
       $.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches(data)); 
      }); 
     }); 


     function processSwitches(data) { 
     alert('processSwitches'); 
     var infoHTML = '<p>Switch Name: ' + data.switchName +'</p>' ; 
     alert(infoHTML); 
     $('#info').html(infoHTML); 
     $('#header').html('<h1>Switches</h1>'); 
     } 
    </script> 
    </body> 
    </html> 

它運行,並將與infoHTML字符串返回正確的警報,但我不能找出爲什麼它不會更新id爲info的div標籤。

誰能幫助?

謝謝。

+0

您是否嘗試刪除ID和名稱之間的空格? Like - > id =「info」 – Smartis

+0

它們是id屬性和等號和屬性值之間的空格? – tschiela

+0

你是不是阻止瀏覽器默認提交形式 – charlietfl

回答

3

您正在調用$.getJSON函數中的processSwitches函數。你應該通過唯一的名稱功能 - 無需(data)部分:

$.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches); 

簡單地說,這樣的:

processSwitches 

,而不是這樣的:

processSwitches(data) 

編輯:

你也忘了阻止形式f rom提交。只需在submit事件處理程序的末尾添加return false

$('#name').submit(function() { 
    alert('submitted'); 
    var switchName = $('#switch').val(); 
    $.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches); 

    return false; 
}); 
+0

好吧,我做到了,但它仍然沒有更新div標籤。 – AkshaiShah

+0

@AkshaiShah您的網頁在您點擊提示上的「確定」後可能會刷新。看我的編輯。 – matewka

+0

哦,完美!謝謝! – AkshaiShah

1

它看起來像你提交表單。在表單提交後數據丟失。

嘗試增加

return false 

$.getJSON(...)