javascript - Are these methods to send JSON using Ajax equivalent? -
i continue see 2 different approach send json data through http request using jquery ajax can't understand correct , have drawbacks.
are equivalent? 1 of these correct less drawbacks?
first approach (implicit serialization)
$.ajax({ url: 'test.php', type : "post", datatype : 'json', data : javascriptobject, success : function(result) { ... }, error: function() { ... } })
data sent server. converted query string, if not string...object must key/value pairs
in case seems me if have javascript object like
var = { name: 'a', age: 10 }
i don't need serialize before send because jquery me giving output string check=check2&radio=radio1
. possibly can json_encode
query string on server-side have json data again.
second approach (serialize(); json.stringify(); serializearray())
1.serialize()
$.ajax({ url: 'test.php', type : "post", datatype : 'json', data : $("#form").serialize(), success : function(result) { ... }, error: function() { ... } })
the .serialize() method creates text string in standard url-encoded notation.
in case understood serialize()
create query string check=check2&radio=radio1
. possibly can json_encode
query string on server-side have json data again. i'd in case serialize()
acts implicit serialization in first approach.
2. json.stringify(), serializearray()
$.ajax({ url: 'test.php', type : "post", datatype : 'json', data : json.stringify($("#form").serializearray()), success : function(result) { ... }, error: function() { ... } })
the .serializearray() method creates javascript array of objects, ready encoded json string.
like (2 , 1 text form)
[ { name: "a", value: "1" }, { name: "b", value: "2" } ]
the stringify function returns string in json format representing ecmascript value... value parameter ecmascript value, object or array...
producing output string
'[{"name": "a","value": "1"},{"name": "b",value: "2"}]'
which can encode json data again.
thanks
Comments
Post a Comment