Json在PHP与JS之间传输
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之间传输的更多相关文章
- php 和 js之间使用json通信
有时候我们需要用后台从数据库中得到的数据在js中进行处理,但是当从php中获取到数据的时候,使用的是键值对形式的多维关联数组.而我们知道,js只支持索引数组,不支持关联数组,这个时候从后台传递过来的数 ...
- java中 json和bean list map之间的互相转换总结
JSON 与 对象 .集合 之间的转换 JSON字符串和java对象的互转[json-lib] 在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级 ...
- 【WP开发】不同客户端之间传输加密数据
在上一篇文章中,曾说好本次将提供一个客户端之间传输加密数据的例子.前些天就打算写了,只是因一些人类科技无法预知的事情发生,故拖到今天. 本示例没什么技术含量,也没什么亮点,Bug林立,只不过提供给有需 ...
- 不制作证书是否能加密SQLSERVER与客户端之间传输的数据?
不制作证书是否能加密SQLSERVER与客户端之间传输的数据? 在做实验之前请先下载network monitor抓包工具 微软官网下载:http://www.microsoft.com/en-us/ ...
- js中json字符串转成js对象
json字符串转成js对象我所知的方法有2种: //json字符串转换成json对象 var str_json = "{name:'liuchuan'}"; //json字符串 / ...
- Python不同电脑之间传输文件实现类似scp功能不输密码
SCP vs SFTP 通过paramiko还可以传输文件,如何通过paramiko在计算机之间传输文件,通过阅读官方文档,发现有如下两种方式: sftp = paramiko.SFTPClient. ...
- OC和JS之间的交互
OC和JS之间的交互 目录 对OC和JS之间交互的理解 JS调用OC OC调用JS 对OC和JS之间交互的理解 JS调用OC JS文件 function sendCommand(cmd,param){ ...
- HTML,CSS,JS之间的关系
HTML,CSS,JS之间的关系 本笔记是自己在浏览了各位前辈后拼凑总结下来的知识,供自己使用消化.后面会附上各种链接地址,尊重原创 最准确的网页设计思路是把网页分成三个层次,即:结构层(HTML). ...
- Linux 两台服务器之间传输文件和文件夹
今天处理一个项目要迁移的问题,突然发现这么多图片怎么移过去,可能第一时间想到的是先从这台服务器下载下来,然后再上传到另外一台服务器上面去,这个方法确实是可行,但是实在是太费时间了,今天我就教大家怎么快 ...
随机推荐
- 中大东校小米路由器mini实现inode上网,ipv6 wifi【中大】【东校】【inode】【ipv6】
还有不到4个月就要毕业了,前几天半夜没事捣鼓小米路由没想到竟然实现了wifi的ipv6. 正好又安利了同学一台小米路由mini,从刷机到inode到ipv6全搞了一遍. 这里将教程写出来,服务学弟妹. ...
- LeetCode题解-----Sliding Window Maximum
题目描述: Given an array nums, there is a sliding window of size k which is moving from the very left of ...
- LinkedList<E>源码分析
LinkedList的数据结构就是双向链表,如下所示: private static class Node<E> { E item;//数据元素 Node<E> next;// ...
- 属性类:Properties
属性是程序中经常出现的形式. 在类集中提供了一种专门的Properties类. public class Propertiesextends Hashtable<Object,Object> ...
- [LeetCode] Binary Tree Upside Down 二叉树的上下颠倒
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that ...
- JS组件系列——BootstrapTable 行内编辑解决方案:x-editable
前言:之前介绍bootstrapTable组件的时候有提到它的行内编辑功能,只不过为了展示功能,将此一笔带过了,罪过罪过!最近项目里面还是打算将行内编辑用起来,于是再次研究了下x-editable组件 ...
- ABP模块化
基于Abp模块化.插件化的设计,开发人员可以将自定义的功能以模块的形式集成到项目中. 模块的加载 模块: 插件: 模块及插件的加载路线: 1. 扩展的HttpApplication对象(在Abp.We ...
- NBUT 1457 莫队算法 离散化
Sona Time Limit:5000MS Memory Limit:65535KB 64bit IO Format: Submit Status Practice NBUT 145 ...
- Power BI REST API
Overview of Power BI REST API https://msdn.microsoft.com/en-us/library/dn877544.aspx 验证方式 OAuth 2.0 ...
- css 固定HTML表格的宽度
在网页中插件表格时,就算你有时定义了宽度,默认的也会根据里面内容的来自动拉伸.有时候自动拉伸是好,但是如果你表格里面的内容太长,表格就会拉伸的特别难看. 像下面的表格,正常的显示应该如下: 但是如果里 ...