[英]Converting serialized form data into json object using Jquery?
I am trying to get data from my form and then send it to a servlet. 我试图从表单中获取数据,然后将其发送到servlet。 But then I notice that the json object that I am getting after serializing my form is not a valid json object.
但是然后我注意到序列化表单后得到的json对象不是有效的json对象。 What could I be doing wrong?
我可能做错了什么? This is what I tried so far.
这是我到目前为止尝试过的。
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var data = $("#register").serialize().split("&");
var obj={};
for(var key in data)
{
console.log(data[key]);
obj[data[key].split("=")[0]] = data[key].split("=")[1];
}
console.log(obj);
// store json string
$.ajax({
type: "POST",
url: "HomeServlet",
dataType: "text",
contentType: "application/json",
data:{"res":obj},
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
</script>
The json object that i am getting from the form is - 我从表单中获取的json对象是-
{
apiname: "jdjdj",
apiendpoint: "sdjsdj",
apiversion: "djdjd",
source: "internet"
}
This is what I want - 这就是我要的 -
{
"apiname": "jdjdj",
"apiendpoint": "sdjsdj",
"apiversion": "djdjd",
"source": "internet"
}
There is nothing wrong with the json you Got . 你得到的json没什么错。
Just stringify it to get the desired object 只需对其进行字符串化处理即可获得所需的对象
var myJSON1 = JSON.stringify(data);
this will work 这会工作
你可以试试看
JSON.stringify(json_data);
As others have noted, your passing a raw javascript object. 正如其他人指出的那样,您传递的是原始javascript对象。 What you must do is convert this object prior to sending it over the wire.
您必须做的是先转换此对象,然后再通过电线发送它。
JSON.stringify(json_data);
Instead of this foreach loop only use serializeArray() then json_parse() these two functions will work for you. 代替此foreach循环,仅使用serializeArray(),然后使用json_parse()这两个函数将对您有用。
var data = $("#register").serializeArray();
var obj= JSON_parse(JSON_stringify(data));
请使用JSON.stringify(obj, undefined, 2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.