开发者

JavaScript array to PHP array then process in PHP and return

开发者 https://www.devze.com 2022-12-27 17:16 出处:网络
Example: javascript: var mycourses=new Array(); mycourses[0]=\"History\"; mycourses[1]=\"Math\"; mycourses[1][0]=\"Introduction to math\";

Example:

javascript:

var mycourses=new Array(); 
mycourses[0]="History";       
mycourses[1]="Math";
mycourses[1][0]="Introduction to math";
mycourses[1][1]="Math 2";
mycourses[1][2]="Math 3";

PHP will then run these values through functions (please note values are mostly not strings as in the example above but rather numbers), the functions will return some text which will than be display开发者_如何学JAVAed in a form

How should I go about doing this?

p.s.: I found some similar stuff, but nothing quite like this... as far as I see I will have to use JSON (is there a way to code it from JS automatically - saw this for strings) and AJAX


Yes, you may use JSON and PHP's json_encode() and json_decode() functions for that.


There are libraries in JavaScript... that will automatically convert your Array to JSON, and in php there are function to convert from JSON to a PHP Array... you process encode again in PHP and decode in JS...

JSON is an standard for JS.. try to use it since most languages already offer support for it, and it would make your life easier


Client-side, you need to send the data to the server and get back the result. This is a sample code with jquery, but you can do similar things with another lib or pure js:

$.post( "compute_courses.php", mycourses )
  .done(function( data ) {
     // Handle result
  })
  .fail(function( jqXHR, textStatus, errorThrown ) {
    // Handle error here
  });

This will send mycourses array to compute_courses.php, and handle the result.

Server-side, it depends which framework/lib you are using, but you will need to read the json, apply treatment, and return a result (most likely with json_encode). If you are planning to write that part yourself (with no third-party framework/lib), you can try something like :

$input = file_get_contents("php://input");
$mycourses = json_decode($input, true);
// Treatment...
$json_result = json_encode($mycourses);
exit($json_result);

If you are looking for a PHP framework that helps to do that kind of stuff, I suggest you to use Silex or Slim.

0

精彩评论

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