1. JS-->PHP

a). JS create Json

 <script>
$(document).ready(function(){
/*--JS create Json--*/
var jsonObject={}; // In another way: jsonObject={'name':"Bruce",'age':25};
jsonObject['name'] = "Bruce";
jsonObject['age'] = 25;
console.log(jsonObject);
console.log('This is stringfied json object: ' + JSON.stringify(jsonObject));
console.log(JSON.parse(JSON.stringify(jsonObject)));
$("#demo").html(jsonObject.name + ", " +jsonObject.age);
/*--JS create Json--*/ });
</script>

Js code create json array object

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

 

 <script>
$(document).ready(function(){
/*--JS create Json--*/
var jsonObject={}; // In another way: jsonObject={'name':"Bruce",'age':25};
jsonObject['name'] = "Bruce";
jsonObject['age'] = 25;
console.log(jsonObject);
console.log('This is stringfied json object: ' + JSON.stringify(jsonObject));
console.log(JSON.parse(JSON.stringify(jsonObject)));
$("#demo").html(jsonObject.name + ", " +jsonObject.age);
/*--JS create Json--*/ /*--Ajax pass data to php--*/
$.ajax({
url: 'php/test.php',
type: 'POST', //or use type: 'GET', then use $_GET['json'] or $_POST['json'] to in PHP script
data: { json: JSON.stringify(jsonObject)},
success: function(response) {
console.log(response);
var jsonObj = JSON.parse(response);
$("#demo").html("From PHP's echo: " + jsonObj.name + ", " + jsonObj.age);
}
});
/*--Ajax pass data to php--*/ });
</script>

JS side

 <script>
$(document).ready(function(){
/*--JS create Json--*/
var jsonObject={}; // In another way: jsonObject={'name':"Bruce",'age':25};
jsonObject['name'] = "Bruce";
jsonObject['age'] = 25;
console.log(jsonObject);
console.log('This is stringfied json object: ' + JSON.stringify(jsonObject));
console.log(JSON.parse(JSON.stringify(jsonObject)));
$("#demo").html(jsonObject.name + ", " +jsonObject.age);
/*--JS create Json--*/ /*--Ajax pass data to php--*/
$.ajax({
url: 'php/test.php',
type: 'POST', //or use type: 'GET', then use $_GET['json'] or $_POST['json'] to in PHP script
data: { json: JSON.stringify(jsonObject)},
success: function(response) {
console.log(response);
var jsonObj = JSON.parse(response);
$("#demo").html("From PHP's echo: " + jsonObj.name + ", " + jsonObj.age);
}
});
/*--Ajax pass data to php--*/ });
</script>

PHP side

2. PHP-->JS

a). PHP create Json

 

 <?php

     $arr = array(
'name' => "Bruce",
'age' => 25,
);
echo json_encode($arr); // {"name":"Bruce","age":25}
echo $arr['name']; // Bruce
echo JSON_decode(json_encode($arr))->{'name'};// Bruce
echo implode((array)json_encode($arr)); // {"name":"Bruce","age":25} ?>

PHP code

b). PHP cURL Call RESTful web service

 <?php

 try {
$data = $_POST['json'];
//echo $data; try {
$rest_url = "";
//echo $rest_url;
//$host = array("Content-Type: application/json; charset=utf-8");
$header = array(
'Content-Type: application/json',
'Centent-Length:'.strlen($data)
//'Content-Disposition: attachment; filename=template1.xlsx'
); $ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_URL, $rest_url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch); echo $output;
} catch (Exception $e) {
echo $e -> getMessage();
} }catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} ?>

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

Json在PHP与JS之间传输的更多相关文章

  1. php 和 js之间使用json通信

    有时候我们需要用后台从数据库中得到的数据在js中进行处理,但是当从php中获取到数据的时候,使用的是键值对形式的多维关联数组.而我们知道,js只支持索引数组,不支持关联数组,这个时候从后台传递过来的数 ...

  2. java中 json和bean list map之间的互相转换总结

    JSON 与 对象 .集合 之间的转换 JSON字符串和java对象的互转[json-lib]   在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级 ...

  3. 【WP开发】不同客户端之间传输加密数据

    在上一篇文章中,曾说好本次将提供一个客户端之间传输加密数据的例子.前些天就打算写了,只是因一些人类科技无法预知的事情发生,故拖到今天. 本示例没什么技术含量,也没什么亮点,Bug林立,只不过提供给有需 ...

  4. 不制作证书是否能加密SQLSERVER与客户端之间传输的数据?

    不制作证书是否能加密SQLSERVER与客户端之间传输的数据? 在做实验之前请先下载network monitor抓包工具 微软官网下载:http://www.microsoft.com/en-us/ ...

  5. js中json字符串转成js对象

    json字符串转成js对象我所知的方法有2种: //json字符串转换成json对象 var str_json = "{name:'liuchuan'}"; //json字符串 / ...

  6. Python不同电脑之间传输文件实现类似scp功能不输密码

    SCP vs SFTP 通过paramiko还可以传输文件,如何通过paramiko在计算机之间传输文件,通过阅读官方文档,发现有如下两种方式: sftp = paramiko.SFTPClient. ...

  7. OC和JS之间的交互

    OC和JS之间的交互 目录 对OC和JS之间交互的理解 JS调用OC OC调用JS 对OC和JS之间交互的理解 JS调用OC JS文件 function sendCommand(cmd,param){ ...

  8. HTML,CSS,JS之间的关系

    HTML,CSS,JS之间的关系 本笔记是自己在浏览了各位前辈后拼凑总结下来的知识,供自己使用消化.后面会附上各种链接地址,尊重原创 最准确的网页设计思路是把网页分成三个层次,即:结构层(HTML). ...

  9. Linux 两台服务器之间传输文件和文件夹

    今天处理一个项目要迁移的问题,突然发现这么多图片怎么移过去,可能第一时间想到的是先从这台服务器下载下来,然后再上传到另外一台服务器上面去,这个方法确实是可行,但是实在是太费时间了,今天我就教大家怎么快 ...

随机推荐

  1. Linux安装详情图解

    本文讲解Linux的安装 因为是纯属学习使用,所以安装在了虚拟机里   需要软件: VirtualBox-5.1.10 ubuntu-16.04.1-desktop-amd64 说明: 虚拟机可以选择 ...

  2. JMeter常见问题集合

    前言 本文内容仅仅是针对Jmeter的部分功能名词的介绍和解释,以及初学者不易理解的问题的整理.部分内容来自别人做的整理,为了更好地整理自己的思路,所以可耻的整理一下发到博客上. 标题[1-6]和[参 ...

  3. PHP加密技术

    一.MD5加密 直接干,这里以一个登录页面为例: <?php require_once 'config/database.config.php'; $act=$_REQUEST['act']; ...

  4. Java的JDBC操作

    Java的JDBC操作 [TOC] 1.JDBC入门 1.1.什么是JDBC JDBC从物理结构上来说就是java语言访问数据库的一套接口集合,本质上是java语言根数据库之间的协议.JDBC提供一组 ...

  5. jmeter(九)逻辑控制器

    jmeter中逻辑控制器(Logic Controllers)的作用域只对其子节点的sampler有效,作用是控制采样器的执行顺序. jmeter提供了17种逻辑控制器,它们各个功能都不尽相同,大概可 ...

  6. Linux Posix线程条件变量

    生产者消费者模型 .多个线程操作全局变量n,需要做成临界区(要加锁--线程锁或者信号量) .调用函数pthread_cond_wait(&g_cond,&g_mutex)让这个线程锁在 ...

  7. Coursera上一个不错的Java课

    地址:https://www.coursera.org/learn/java-chengxu-sheji/home/welcome 复习天昏地暗,看点视频调剂一下.发现这个讲的还是很不错的.北大毕竟比 ...

  8. [LeetCode] Minimum Number of Arrows to Burst Balloons 最少数量的箭引爆气球

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  9. HTTP服务器(1)

    单文件服务器 导语 在研究HTTP服务器时,我们可以从一个单文件服务器开始.无论接受到什么请求,这个服务器始终发送同一个文件.下面是示例代码,绑定的端口,发送的文件名以及文件的编码从命令行读取.如果省 ...

  10. oracle日常——数据库备份

    1.进入cmd 2.运行命令 exp [scott]/[orcl]@[orcl] file=[d:\oracle_back\scott_orcl.dmp] owner=scott 格式如下: exp ...