If you are currently using Restful API and you need to build a json format string response through a web project, then this article will help you use javascript to create a json format string. This is very useful, we will convert the data object to json format through the jQuery plugin $.toJSON.
Using JavaScript to build a JSON format string
Javascript code:
The javascript code is included here. $(“#form”).submit(function(){}- delete_button is the ID of the form tag. We call the value of the form input box through element.val(). The code is as follows:
HTML code:
JSON output
{
"userDetails":{
"user":{
"name":"Srinivas Tamada",
"email":"srinivas@9lessons.info",
"password":"Srinivas Tamada",
"gender":"male",
"websites":["www.software8.co","www.heatpress123.net","www.0769zzw. com"]
}
}
}
JSON Encoded
To encode special characters, the following characters will be encoded :
, / ? : @ & = $ #
jsondata= {"userDetails":{"user":{"name":"Srinivas Tamada","email":"srinivas@9lessons.info","password":"Srinivas Tamada","gender":"male"," websites":["www.9lessons.info","www.egglabs.in","www.fglogin.com"]}}}
GetPostAjax.js
jquery is defined here ajax request method.
function post_data(url,encodedata, success){
$.ajax({
type:"POST",
url:url,
data :encodedata,
dataType:"json",
restful:true,
contentType: 'application/json',
cache:false,
timeout:20000,
async:true,
beforeSend :function(data) { },
success:function(data){
success.call(this, data);
},
error:function(data){
alert("Error In Connecting");
}
});
}
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn