我正在编写一个函数,将表单中的数据发布到REST API。这是我拥有的内容,但它没有起作用,我无法弄清原因。
<script>
console.log(document);
var form = document.getElementById("myform");
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
function addData(){
$.ajax({
type: "POST",
url: "http://example.com",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
alert(success);
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
alert('fail' + status.code);
}
});
}
</script>
有人能指点我正确的方向吗?