我正在尝试将表单数据发布到我的服务器。我已经编写了以下 ajax 调用,但我不断收到 400 Bad 错误。有什么帮助吗?
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: "/compare",
type : "POST",
contentType : 'application/json; charset=utf-8',
data : $('#form').serialize(),
success : function(result) {
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
以下是我的 HTML 表单:
<form id="form">
<p>Input the URL of 2 images!</p>
<input id="img1" name="img1" type="text" placeholder="Image 1 URL">
<input id="img2" name="img2" type="text" placeholder="Image 2 URL">
<input id="submit" type="submit" value="Compare!">
</form>
最佳答案
由于您尝试将 JSON 发送到服务器,因此您可以使用数据创建一个对象,然后在将其发送到服务器之前对其进行字符串化。
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
var img1 = $("#img1").val();
var img2 = $("#img2").val();
var myData = {img1: img1, img2: img2};
$.ajax({
url: "/compare",
type : "POST",
contentType : 'application/json; charset=utf-8',
data : JSON.stringify(myData),
success : function(result) {
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
关于javascript - Ajax 提交表单时收到 400 Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46776107/