简体   繁体   中英

How to do a non-ajax POST of JSON using Javascript/jQuery?

I've got a website in which I collect all sorts of data, most of it coming from a dynamically built form. Upon a user clicking a button I now want to take all that information, do a POST to the current page with the collected data as JSON, which will redirect the user to another (success) page.

So far I can catch the user click on the button and collect all the data. I know that I can do an ajax post using something like this:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

the thing is that I don't want to do it in the background. Since the posting of the data will redirect the user to another page, it should do it like a regular post, but I don't know how to do that in Javascript.

Any ideas how I could put the vars in json and do a regular post of this json to the server? All tips are welcome!

The only way to make a POST request from an HTML document other then via XMLHttpRequest is by submitting a form, and application/json is not a supported encoding type for HTML forms.

You would need to adjust the server side program to handle one of the standard form data encodings and then submit a regular form to it.

Why not just post it in AJAX JSON and then use window.location.href in the success function (Callback available from the AJAX)

That way you would be able to post all your POST VARS in the data sction of the json.

do your ajax call, then reload the page on success

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: window.location.href=$(input[name=reloadURL]).attr('value'),
  dataType: dataType
});

you can store the url in a hidden input when you first show the page

<input type="hidden" name="reloadURL" value="www.example.com">

that is if the url can change, otherwise write it right away in the success clause of the ajax call like a normal string:

success: window.location.href='www.example.com',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM