我正在创建一个 URL 缩短器,但在获取 jquery 表单值以便输出缩短的 URL 文本时遇到一些问题。
Here是我正在使用的表格:
<form name="urlForm">
<input type="text" name="url">
<button id="submit" type="button">Submit</button>
<p>Result:
<!-- Output area. -->
<span id="url-output"></span> </p>
</form>
和here是我用来处理表单数据的 JavaScript:
// receive the form when "submit" button is clicked
$('form[name=urlForm]').submit(function (event) {
console.log('form submitted');
// get the data in the form
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
//element[attribute=value]
'name': $('input[name=url]').val(),
};
// process the form
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: '/createShorter', // the url where we want to POST
data: formData, // our data object
dataType: 'json', // what type of data do we expect back from the server
encode: true
})
// using the done promise callback
.done(function (data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
我认为问题在于我如何收集 formData 变量中的数据。但是,尽管查看了文档并进行了多次不同的尝试,但我所做的一切似乎都没有输出任何相关值。我采取了不好的方法吗?
如何解析我的表单以获取所需的信息?
最佳答案
该代码段无法运行(严格安全),请查看 PLUNKER 相反。 Plunker 演示了如何使用正确制作的表单、使用纯 JavaScript XMLHttpRequest()
、发布到真实的测试服务器并接收 json 响应。详细信息在代码片段中评论。
片段(不起作用)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!--Use id and name, although name isn't used in this instance, it can be useful under different circumstances-->
<form id='urlForm' name="urlForm">
<input type="text" id='url' name="url">
<!--Use an input type submit button instead, it will automatically trigger a submit event once clicked-->
<input id="submit" type="submit">
<br/>
<label>Result:
<!--Using a real output element allows you to display data with the value property or with content methods such as innerHTML or textContent-->
<output id="urlOutput"></output>
</label>
</form>
<script>
// Reference the form
var f1 = document.getElementById('urlForm');
// Reference the output
var o1 = document.getElementById('urlOutput');
// When a submit event is triggered...
f1.onsubmit = function(e) {
// Prevent the form from submitting normally
e.preventDefault();
// reference a XHR object
var req = new XMLHttpRequest();
// POST to server
req.open('POST', 'http://httpbin.org/post', false);
// reference a FormData object
var formData = new FormData(f1);
req.send(formData);
o1.value = req.response;
}
</script>
</body>
</html>
关于javascript - 存储和输出表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40539899/