我是新來的HTML和Java腳本。我嘗試創建一個按鈕並從URL獲取JSON,並將結果添加到下拉列表中。 Nodejs服務器啓動並運行後,如果輸入http://localhost:8080/restapi/test/projects,則會返回{example}作爲結果。按鈕點擊不工作jquery
所以這裏還有幾個問題: 1)由於某種原因,按一下按鈕是不是裏面的jQuery 2)$ .getJSON只能內部使用jQuery的工作,有沒有其他的方式來從URL獲得響應JSON ?
$(document).ready(function() {
$(document).on('click', '#button1', function() {
var selector = document.getElementById('selector');
var api = 'http://localhost:8080/restapi/test/projects';
$.getJSON(api, function (data) {
$.each(data, function (index, d) {
var option = document.createElement('option');
option = d;
selector.add(option);
});
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id='first'>
<h1>project options</h1>
<button id='button1'>Get Projects</button>
</div>
<div id='second'>
<h2>all projects</h2>
Projects: <select id='selector'></select>
</div>
感謝您的任何提示。
您可以使用Ajax也爲獲得來自URL – Learner
你肯定不會需要JSON響應使用jQuery(或任何其他庫)在JS中執行任何操作,包括髮出Web請求。然而,你會發現圖書館使許多事情變得更簡單,因爲工作已經爲你完成了,沒有理由重新發明輪子。如果您想在沒有jQuery的情況下發出AJAX請求,請查看內置的['XMLHttpRequest'](http://www.w3schools.com/xml/dom_httprequest.asp)對象。這是jQuery使用簡單的東西:) –
按鈕點擊正在工作,yu可以通過在該點擊功能中放置警報或控制檯來檢查它。 – Learner