Json在PHP与JS之间传输

1. JS-->PHP

a). JS create Json 

 

 1 <script>
 2     $(document).ready(function(){
 3         /*--JS create Json--*/
 4         var jsonObject={};   // In another way: jsonObject={'name':"Bruce",'age':25};
 5         jsonObject['name'] = "Bruce";
 6         jsonObject['age'] = 25;
 7         console.log(jsonObject);
 8         console.log('This is stringfied json object: ' + JSON.stringify(jsonObject));
 9         console.log(JSON.parse(JSON.stringify(jsonObject)));
10         $("#demo").html(jsonObject.name + ", " +jsonObject.age);
11         /*--JS create Json--*/
12         
13     });
14 </script>
Js code create json array object

 

b). Pass Json from JS to PHP by using Ajax

 

 1 <script>
 2     $(document).ready(function(){
 3         /*--JS create Json--*/
 4         var jsonObject={};   // In another way: jsonObject={'name':"Bruce",'age':25};
 5         jsonObject['name'] = "Bruce";
 6         jsonObject['age'] = 25;
 7         console.log(jsonObject);
 8         console.log('This is stringfied json object: ' + JSON.stringify(jsonObject));
 9         console.log(JSON.parse(JSON.stringify(jsonObject)));
10         $("#demo").html(jsonObject.name + ", " +jsonObject.age);
11         /*--JS create Json--*/
12         
13         /*--Ajax pass data to php--*/
14         $.ajax({
15             url: 'php/test.php',
16             type: 'POST',          //or use type: 'GET', then use $_GET['json'] or $_POST['json'] to in PHP script
17             data: { json: JSON.stringify(jsonObject)},
18             success: function(response) {
19                 console.log(response);
20                 var jsonObj = JSON.parse(response);
21                 $("#demo").html("From PHP's echo: " + jsonObj.name + ", " + jsonObj.age);
22             }
23         });
24         /*--Ajax pass data to php--*/
25         
26     });
27 </script>
JS side

 

 1 <script>
 2     $(document).ready(function(){
 3         /*--JS create Json--*/
 4         var jsonObject={};   // In another way: jsonObject={'name':"Bruce",'age':25};
 5         jsonObject['name'] = "Bruce";
 6         jsonObject['age'] = 25;
 7         console.log(jsonObject);
 8         console.log('This is stringfied json object: ' + JSON.stringify(jsonObject));
 9         console.log(JSON.parse(JSON.stringify(jsonObject)));
10         $("#demo").html(jsonObject.name + ", " +jsonObject.age);
11         /*--JS create Json--*/
12         
13         /*--Ajax pass data to php--*/
14         $.ajax({
15             url: 'php/test.php',
16             type: 'POST',          //or use type: 'GET', then use $_GET['json'] or $_POST['json'] to in PHP script
17             data: { json: JSON.stringify(jsonObject)},
18             success: function(response) {
19                 console.log(response);
20                 var jsonObj = JSON.parse(response);
21                 $("#demo").html("From PHP's echo: " + jsonObj.name + ", " + jsonObj.age);
22             }
23         });
24         /*--Ajax pass data to php--*/
25         
26     });
27 </script>
PHP side

 

2. PHP-->JS

a). PHP create Json

 

 1 <?php
 2     
 3     $arr = array(
 4         'name' => "Bruce",
 5         'age' => 25,
 6     );
 7     echo json_encode($arr);                       //  {"name":"Bruce","age":25}
 8     echo $arr['name'];                            //  Bruce
 9     echo JSON_decode(json_encode($arr))->{'name'};//  Bruce
10     echo implode((array)json_encode($arr));       //  {"name":"Bruce","age":25}
11     
12 ?>
PHP code

 

b). PHP cURL Call RESTful web service

 

 1 <?php
 2 
 3 try {
 4     $data = $_POST['json'];
 5     //echo $data;
 6 
 7     try {
 8         $rest_url = "";
 9         //echo $rest_url;
10         //$host = array("Content-Type: application/json; charset=utf-8");
11         $header = array(
12             'Content-Type: application/json',
13             'Centent-Length:'.strlen($data)
14             //'Content-Disposition: attachment; filename=template1.xlsx'
15         );
16         
17         $ch = curl_init();
18         curl_setopt($ch, CURLOPT_HEADER, 0);
19         curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
20         curl_setopt($ch, CURLOPT_URL, $rest_url);
21         curl_setopt($ch, CURLOPT_VERBOSE, 1); 
22         curl_setopt($ch, CURLOPT_POST, true);
23         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
24         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
25         $output = curl_exec($ch);
26     
27                 echo $output;
28     } catch (Exception $e) {
29         echo $e -> getMessage();
30     }
31 
32 }catch (Exception $e) {
33     echo 'Caught exception: ',  $e->getMessage(), "\n";
34 }
35 
36 ?>
PHP cURL code

 

3. Pass Json from PHP to PHP (must be array then json_encode('json string')?)

 

http://stackoverflow.com/questions/871858/php-pass-variable-to-next-page

 

4. Submit parameters to PHP through HTML form POST/GET to download a file (e.g. Excel...)

 

 I figure out a way around this. Instead of making a POST call to force the browser to open the save dialog, I will make a POST call to generate the file, then temporary store the file on the server, return the filename . Then use a GET call for this file with "Content-Disposition: attachment; filename=filename1". The GET call with that header will force the browser to open the "Save this file" dialog, always.

<?php
    require_once 'RESTClient.php';
    $url = 'http://158.132.51.202/SWR-SHRS/API/V1/';
    //echo $url;
    
    $type = 1;
    if(!empty($_GET['type'])){
       $type = trim($_GET['type']);
    }
    $data = $_GET['filter'];

    $client = new SHRRESTClient($url);
       $path = $client->downloadExcel($dataId['studid'], (array)json_decode($data));
    if($type == 0){
        echo "http://localhost/php/".$path;
    }else{
        // send header information to browser
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;');
        header('Content-Disposition: attachment;  filename="helpers_list.xlsx"');
        header('Content-Length: ' . filesize($path));
        header('Expires: 0');
        header('Cache-Control: max-age=0');
        //stream file
        flush();
        print file_get_contents($path);
        unlink($path);   //delete the php server side excel data
    }
    
?>
exportFile.php
<?php

class SHRRESTClient{
    
    public $base_url = null;
    public function __construct($base_url = null)
    {
        if (!extension_loaded('curl')) {
            throw new \ErrorException('cURL library is not loaded');
        }
        $this->base_url = $base_url;
    }

    public function downloadExcel($sid, $data){
        $url = $this->base_url.$sid.'/...url...';
        $data_string = json_encode($data);
        # open file to write
        $path = 'tmp/'.$sid.'.xlsx';
        $fp = fopen ($path, 'w+');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json', 
        'Content-Length: ' . strlen($data_string))
        );
        # write data to local file
        curl_setopt($ch, CURLOPT_FILE, $fp );
        $result = curl_exec($ch);
        # close local file
        fclose( $fp );
        curl_close($ch);
        return $path;
    }
}
?>
RESTClient.php

 

posted @ 2015-08-01 22:38  bruceyo  阅读(361)  评论(0编辑  收藏  举报