Javascript Java脚本-隐藏格式字段中的JSON
是否可以使用来自隐藏表单字段的JSON内容发送帖子 我的表单如下所示:Javascript Java脚本-隐藏格式字段中的JSON,javascript,json,Javascript,Json,是否可以使用来自隐藏表单字段的JSON内容发送帖子 我的表单如下所示: <form method="POST" name="form0" action="https://my_url/comment/id?Id=5"> <input type="hidden" name="id" id="inputField" value='{"number":5,"content":"aaaa"}'/> </form> 它是以字符串形式发送的。是的,您可以这样做。但您需
<form method="POST" name="form0" action="https://my_url/comment/id?Id=5">
<input type="hidden" name="id" id="inputField" value='{"number":5,"content":"aaaa"}'/>
</form>
它是以字符串形式发送的。是的,您可以这样做。但您需要在服务器端对其进行解码,因为它将作为字符串传输 使用jQuery,这将非常容易实现:
$.post('https://my_url/comment/id?Id=5', {"number":5,"content":"aaaa"});
您甚至可以传递回调以对返回的内容作出反应:
$.post('https://my_url/comment/id?Id=5', {"number":5,"content":"aaaa"}, function (response){
// Do something cool here.
});
HTML表单只能将数据编码为application/x-www-form-urlencoded、multipart/form data或text/plain,后者没有任何实际用途 您现有的代码将对其中的JSON进行编码 如果要发送应用程序/json编码的表单体,则需要使用XMLHttpRequest或fetch 例如:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/path/to/handler");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({"number":5,"content":"aaaa"}));
JSON.parsewhatToSendjQuery将使用application/x-www-form-urlencoded格式对该数据进行编码。您得到的JSON比原始代码少。同意,但您传递了数据,这基本上就是您想要做的。
var xhr = new XMLHttpRequest();
xhr.open("POST", "/path/to/handler");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({"number":5,"content":"aaaa"}));