如何在提交表单时向服务器发送JSON请求参数?
function fun2() {
alert("in fun2");
document.searchForm.action = "http://localhost:8080/DatasetRepo/rest/downloadZip?"+"{'datasets':['1'],'token':'myfirsttoken'}";
document.forms["searchForm"].submit();}
并且无法使用不支持的媒体类型错误。
答案 0 :(得分:2)
$.post( "test.php", { name: "John", time: "2pm" } );
或
$.get( "test.php", { name: "John", time: "2pm" } );
答案 1 :(得分:0)
使用serialize
获取表单数据,例如
var form=$('form[name=searchForm]');
$.post(url, form.serialize(),callback)
答案 2 :(得分:0)
而不是像json一样发送,只需发送为查询字符串...
function fun2() {
document.searchForm.action = "http://localhost:8080/DatasetRepo/rest/downloadZip?datasets[]=1&token=myfirsttoken";
document.forms["searchForm"].submit();
}
然后,您要发布到的文档将具有$ _GET数组中的值...
<?php
print_r($_GET);
?>
答案 3 :(得分:0)
这可能不是一个好方法,就像你想发送JSON一样,你也需要将Contetn-Type标题设置为application/json
,这样接收服务器就能理解它没有处理URL与典型表单帖子一样的编码查询字符串。大多数浏览器还不支持使用表单enctype="application/json"
,因为这仍然只是HTTP规范的草稿部分。
答案 4 :(得分:0)
使用JSON.stringify函数在ajax帖子中发送json,下面的代码片段可用于使用ajax发送数据。
var data = {
one: 'first',
two: 'second'
};
function formSubmit(url, data) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
ajaxCallback(xmlhttp);
};
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(JSON.stringify(data));
}
function ajaxCallback(xmlhttp) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttp.responseText);
console.log(response);
}
}
希望这有帮助。
答案 5 :(得分:0)
您需要将数据发布到PHP脚本并使用curl发送内容类型并发布数据。
如果您使用的是Java,则类似。见How to use cURL in Java?
在任何一种情况下,您都无法直接从表单发送json内容类型,并且需要使用服务器端脚本来实现您的目标。
希望有所帮助。