I have a web application. On the client side I basically need to get the values of some fields and turn them into JSON and then send them to the server in an AJAX kind of way.(asynchronous)
How would you do that? I also am开发者_JAVA百科 using jQuery
If you want to create JSON (also called stringifying) on the client side, you can use the stringifier from json.org. More details about its use here.
You would then use your normal jQuery.ajax(...)
like so:
function sendJSON(dataToStringify) {
var stringifiedData = JSON.stringify(dataToStringify);
jQuery.ajax({
url: 'http://some.url.here',
data: {stringified: stringifiedData},
success: function(data) {
//code to handle successful AJAX post
},
error(XMLHttpRequest, textStatus, errorThrown) {
//code to handle errors
}
});
}
json2.js allows you to convert JavaScript objects to JSON representations using the JSON.stringify()
function.
$.ajax() will allow you to then pass your string as a query parameter to your server side.
Quick example to tie them both together:
$.ajax({
url: '/someurl',
data: { json: JSON.stringify(myData) }
});
精彩评论