我需要在html上填寫表單時發送json。我有以下的html:如何通過html表單使用jquery,json和ajax?
<head>
<title>Insert title here</title>
</head>
<body>
<form id="form">
Nome: <input type="text" id="nome" />
Idade: <input type="number" id="idade" />
<input type="button" id="submit" value="submit"/>
</form>
及以下JS:
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"
var arr = {
City : 'Moscow',
Age : 25
};
$(document).ready(function() {
//click on button submit
$("#submit").on('click', function() {
//send ajax
$.ajax({
url : 'http://localhost:8080/DBRest/rest/escreve',
type : "POST", // type of action POST || GET
dataType : 'json', // data type
contentType : 'application/json; charset=utf-8',
data : $("#form").serialize(), // post data || get data
data : JSON.stringify(arr)
})
});
});
我試圖創建一個arr
變量來模擬一個填充表單,但沒有得到任何東西。我想知道dataType和contentType之間的區別。並且關於這個特定行:
data : $("#form").serialize()
這是正確的嗎?簡單和雙引號之間有區別#form
你確定這個問題不是表單提交嗎?也許試試用''('#form')。on('submit',function(e){e.preventDefault(); //繼續你正在做的事情});'而不是聽點擊提交按鈕。 – Gavin