0

I'm building REST web app and my server side Java code expects request body to have pure JSON string. My goal is to use regular HTTP POST method (not ajax) and set JSON into request body message.

If I use ajax, it is very simple. Something like:

var jsonInput = '{"foo":"bar"}';
ajaxRequest.setRequestHeader("Content-Type", "application/json");
ajaxRequest.send(jsonInput)

But I want to use regular HTTP POST.

Looking at the thread below, the answer is to create a form with hidden input field and put JSON in to the input field and have server side code handle the rest.

JavaScript post request like a form submit

I tried that and it works just fine but do I really have to bother creating new form and input field to accomplish this? Or is there any other way available?

NOTE: I don't want to use JQuery or Prototype framework. Just simple Javascript.

Community
  • 1
  • 1
Meow
  • 16,125
  • 50
  • 122
  • 176
  • 1
    Unless something has changed since that post I'm pretty sure it is still the only way. – Hamish Feb 28 '11 at 08:02
  • First of all, why not AJAX? Second, why don't you want to use some framework that would make your life easier? I am seriously interested - see [this question](http://stackoverflow.com/questions/5099949/what-are-some-empirical-technical-reasons-not-to-use-jquery) – rsp Feb 28 '11 at 08:20
  • On that web page, I have a submit button to download Excel file but downloading is not allowed via Ajax request. And my team decided not to use any framework. So those factors are out of my control.. – Meow Feb 28 '11 at 08:34

1 Answers1

1

FORMs only allow for name-value pairs to be submitted, and so your JSON needs to be inserted into one such pair.

Yout can read about this at w3.org

As a solution, what about using xhr to send the data to the server, exchange it for some token, and then direct the user via a regular GET to a url passing the token?

This should fit with the REST paradigm too.

Sean Kinsey
  • 35,601
  • 7
  • 49
  • 68