我想发送一个简单的json对象到云端数据库,但我不断收到错误。我设置了云数据库的权限以允许读取,写入和复制。 我已经尝试重写ajax文章,我添加了一个头没有解决错误,但我不断收到错误,似乎无法找到原因。错误415发布JSON文件到云端公共数据库
确切的错误是:
POST https://birdoftravel.cloudant.com/questions/_all_docs/ 415 (Unsupported Media Type)
send @ jquery-1.12.4.min.js:4
ajax @ jquery-1.12.4.min.js:4
saveQuestionToDB @ saveQuestion.js:54
(anonymous) @ saveQuestion.js:77
dispatch @ jquery-1.12.4.min.js:3
r.handle @ jquery-1.12.4.min.js:3
function QuestionObject(q, o, a){
this.question = q;
this.options = o;
this.answer = a;
}
function createQuestion(){
var q = $('#question').val();
console.log("question: "+q);
var o = $('#options').val().split(',');
var a = $('#answer').val();
var question = new QuestionObject(q,o,a);
var jsonQ = JSON.stringify(question);
console.log("json string"+jsonQ);
$('#question').val("");
$('#options').val("");
$('#answer').val("");
return jsonQ;
}
function saveQuestionToDB(){
var urlDB = 'https://birdoftravel.cloudant.com/questions/_all_docs/';
var data = createQuestion();
console.log("data :"+data);
/* $.ajax({
url: urlDB,
type: "POST",
dataType: "application/json",
data: data,
success: function(){
alert('The question was posted!');
},
error: function(err){
console.log("error: "+err+" question not posted: "+data);
}
});*/
$.ajax({
type: "POST",
url: urlDB,
data: data,
success: function(d){
console.log("question was posted!"+d);
},
error: function(e){
console.log("not posted! "+e);
},
dataType: "application/json",
});
}
$('#btn').click(function(e){
saveQuestionToDB();
e.preventDefault();
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="quizStyle.css">
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous">
</script>
<title>Add a new quiz</title>
</head>
<body>
<h2>Enter a new quiz</h2>
<form id="newQuizForm">
Insert question:<br>
<input type="text" id="question"><br>
Insert optional answers seperated by ;<br>
<input type="text" id="options"><br>
Insert correct answer:<br>
<input type="text" id="answer"><br>
<input type="submit" id="btn" value="Save question">
</form>
<script src="saveQuestion.js"></script>
</body>
</html>
即使更改为它,它仍然给出相同的415错误。 我也试着发邮件的邮递员,我得到同样的错误。 { “错误”:“bad_content_type”, “理由”:“内容类型必须是application/JSON” } 发送一个GET工作虽然,我真的不明白为什么它不工作。 – Karima
我发送一个额外的内容类型参数为json,现在它给出了关于json的utf-8的错误。 – Karima
查看我原始回复中的更新。要在Cloudant中启用CORS,请打开** Account **选项卡并选择** CORS **。 – ptitzler