开发者

what's the best way to post 30 variables from client side to server?

开发者 https://www.devze.com 2023-03-10 05:16 出处:网络
hey, i have about 30 variables which are created and modified by user (none of which comes fr开发者_JAVA百科om input, so submitting a form is not really an option), once modification finished a JS fun

hey, i have about 30 variables which are created and modified by user (none of which comes fr开发者_JAVA百科om input, so submitting a form is not really an option), once modification finished a JS function process the variables and spouse to post them to the controller which will then send the to the model.

now, as appears in the title, my question is what is the best way for me to send them?

thnx for time and attention, Ido


I wouldn't use GET for this unless it's something like a complex search form.

You can POST values in JavaScript either by using some form of AJAX or by generating a hidden form and submitting it.


Modern browsers and newer versions of PHP both support JSON, and there are supporting libraries you can use if the browsers you need to support or the PHP version you're stuck with are old. I'd recommend this as a way of getting data back and forth.

Client side JS:

var myobject = {
  userparam: "value",
  anotherThing: "another value",
  something: "etc"
}

var serialized = JSON.stringify(myobject);

// use any AJAX technicque to POST 'serialized' back to the server

Then on the server-side:

<?php

  $myobject = json_decode( $_POST['serialized'], true );

  $myobject['userparam'] == "value"; // true

Hope this helps!


I would use a POST using an ajax-submitted form. You can simply create a form with hidden inputs and then use your favorite ajax library to submit the form to the server as a POST request.


If the variables are tightly related you can shove them into an array and POST them (use Javascript to construct the array of course). Another alternative would be to name each one of them and POST them separately?

POST array look like this: arr[]=Hello&arr[]=World

in PHP you can access it like

<?php
arr = $_POST['arr'] // ["Hello", "World"]
?>

Hope that helped!


Weigh it up between POST and GET. GET is better if you want to navigate back to the a page with a given set of 'variables'. POST is better if you're submitting a lot of content. However, a POST request is less 'efficient' as a GET request - bear that in mind and only use POST if you really need to.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号