SOA, unobtrusive JavaScript
I have a restful web service which can deal with DTOs in json format to perform a CRUD operation.
Let us also say I use jquery in an unobtrusive way t开发者_运维百科o serialise my form at the frontend using:
JSON.stringify
What can I do to ensure that everything works even if JavaScript is switched off?
I don't see how you can run jquery JavaScript when JavaScript is turned off.
Can you have a version of your app that submits the form to the server and have the JSON serialisation done on the server side?
It really depends on what your server-side script is written in, I suppose. Most web app languages have some kind of json support. So if you want your form data to be in json even after it hits the server, use whatever your language supports. In PHP, you could do:
$form_data_json = json_encode($_POST);
Of course that would assume you wanted all of the data passed from the form, which you might not. But that's a simple one-line solution.
The only way to ensure that it works, even with javascript turned off, is to post the information without AJAX and validate and transform all the information on the server. JQuery is JavaScript, so if JS is turned off on the client, it won't work. Most modern server side languages can natively handle serializing/de-serializing JSON, and if not there are sure to be libraries out there to do it for your language of choice.
Have an alternative version that can be gracefully degraded to. JSON cannot be handled without JavaScript (JSON = JavaScript Object Notation)
You don't mention what technologies are you using on the server, so I'll try to make this server-agnostic.
You have to point your form action to a different url than your web service (in rails this would be some other "controller action").
<form id="input_form" action="your/non-SOA/action">
<input type="text" name="user" />
<input type="submit" value="Submit"/>
</form>
Somewhere else (probably on a js file loaded on the head of the html) you should have a javascript code that modifies how the submit "click" event is handled:
$(function(){ // jQuery DOM ready function.
var form = $("#input_form");
var submit_button = $("#input_form .input[type=submit]");
submit_button.bind('click', function() {
// serialize form with JSON and send it here
});
});
This code will execute only if javascript is enabled. If it isn't, then the form will be sent to the your/non-SOA/action
via a POST request, usually in form of 'associative hash' on the action params. So you have to transform this hash into a json structure on the server, and send it to the corresponding web service.
It will look like this in your server (pseudo-code):
function your.non-SOA.action(params)
// you might need more treatment than just doing to_json, depending on your ws syntax
serialized_text = params['input_form'].to_json
myWebservice = Webservice.new('your-webservice-uri')
try
myWebservice.send(serialized_text)
catch(exception e)
// handle exceptions
end
end
精彩评论