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 两台服务器之间传输文件和文件夹
今天处理一个项目要迁移的问题,突然发现这么多图片怎么移过去,可能第一时间想到的是先从这台服务器下载下来,然后再上传到另外一台服务器上面去,这个方法确实是可行,但是实在是太费时间了,今天我就教大家怎么快 ...
随机推荐
- 测试EntityFramework,Z.EntityFramework.Extensions,原生语句在不同的查询中的表现。原来池化与非池化设定是有巨大的影响的。
Insert测试,只测试1000条的情况,多了在实际的项目中应该就要另行处理了. using System; using System.Collections.Generic; using Syste ...
- 安装centos后无法引导启动windows7的解决方法
在电脑Windows7系统上安装Centos7,安装后找不到Windows7引导菜单. 原因:因为CentOS 7已采用新式的grub2系统,所以需要进入/boot/grub2目录后使用vi编辑gru ...
- 安全测试 - 抓包工具BurpSuite
Brup SuiteBurpSuite是用于攻击web应用程序的集成平台.它包含了许多工具,并为这些工具设计了许多接口,以促进加快攻击应用程序的过程.所有的工具都共享一个能处理并显示HTTP消息,持久 ...
- vs2015 编译时错误列表中没有错误,dll却没有生成出来
最近发现vs2015的一个问题, 编译时,错误列表中没有错误,dll却没有生成出来,vs重启也无效 解决: 多次排查发现如果一个类库设置的是framework 4.0版本,但引用了framework4 ...
- mongodb集群安装及到现在遇到的一些问题
集群搭建 只有3台服务器,开始搭建mongodb集群里主要参照的是http://www.lanceyan.com/tech/arch/mongodb_shard1.html,端口的设置也是mongos ...
- [LeetCode] Longest Repeating Character Replacement 最长重复字符置换
Given a string that consists of only uppercase English letters, you can replace any letter in the st ...
- 单点登录改进版-使用ajax分发cookie避免重定向轮询
前言 继上一篇博文:可跨域的单点登录(SSO)实现方案[附.net代码]虽然实现了单点登录,也存在很多不合理的地方.很多热心的朋友也给出了很多指导性的意见,特别是 LoveCoder提出的意见. 在很 ...
- 基于C/S架构的3D对战网络游戏C++框架_01服务器端与客户端需求分析
本系列博客主要是以对战游戏为背景介绍3D对战网络游戏常用的开发技术以及C++高级编程技巧,有了这些知识,就可以开发出中小型游戏项目或3D工业仿真项目. 笔者将分为以下三个部分向大家介绍(每日更新): ...
- 时间格式转换—将后台返回的/Date(1448954018000)/格式转换为正常的时间格式
用JS实现方法: function ChangeDateFormat(cellval) { )); < ? ) : date.getMonth() + ; ? " + date.get ...
- 关于SQL注入和如何防止
之前在笔试的时候没有很好的答出这个问题,因此我要总结一下问题,以免日后继续在这个地方跌倒,以下是自己的理解,如有错误请指出 一.什么是SQL注入 SQL注入就是服务器在根据业务去处理数据库的时候,客户 ...