Json在PHP与JS之间传输

时间:2021-09-19 14:00:06

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://*.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. matlab中数组创建方法

    创建数组可以使用 分号 :  逗号, 空格 数组同行用 逗号,或空格分割 不同行元素用 分号: clc; a = [ ]; b1 = a();%第3个元素 b2 = a(:)%第2//4个元素 b3 ...

  2. TCP&sol;IP连接状态

    1.建立连接协议(三次握手)(1)客户端发送一个带SYN标志的TCP报文到服务器.这是三次握手过程中的报文1.(2) 服务器端回应客户端的,这是三次握手中的第2个报文,这个报文同时带ACK标志和SYN ...

  3. javascript数组浅谈1

    最近心血来潮要开始玩博客了,刚好也在看数组这块内容,第一篇就只好拿数组开刀了,自己总结的,有什么不对的地方还请批评指正,还有什么没写到的方面也可以提出来我进行完善,谢谢~~ 首先,大概说说数组的基本用 ...

  4. android中实现view可以滑动的六种方法续篇(一)

    承接上一篇,如果你没有读过前四章方法,可以点击下面的链接: http://www.cnblogs.com/fuly550871915/p/4985053.html 下面开始讲第五中方法. 五.利用Sc ...

  5. 【Qt】Qt之自定义界面(窗体缩放-跨平台终极版)【转】

    简述 通过上一节内容,我们实现了窗体的缩放,功能很不错,但是很遗憾-不支持跨平台!如果对于多平台来说,这是一个硬伤,所以,我们急需要一个能够支持跨平台的实现方案. 在网上看到过很多不同的实现方式,多多 ...

  6. 【PHP系列】PHP推荐标准之PSR-4,自动加载器策略

    接上回的继续说,上回说到PSR-3日志记录器接口,这回我们来说说PSR的最后一个标准,PSR-4,自动加载器策略. 缘由 自动加载器策略是指,在运行时按需查找PHP类.接口或性状,并将其载入PHP解释 ...

  7. 浅论Python密文输入密码的方法

    近来做作业(老男孩那个9.9元的训练营)我想写一个装逼点的密文输入密码,类似于: 这个东西我先前实现过,忘了获取一个字节的方法是什么,于是去网上找,发现网上的实现方式大部分都有问题. 一.网上(百度) ...

  8. SpringBoot-目录及说明

    今天开始抽时间整理SpringBoot的内容这里可以作为一个目录及说明相关的资料都可以跳转使用 说明: 目录: 一:创建SpringBoot项目 1)Maven创建 (1)使用命令行创建Maven工程 ...

  9. Android滑动列表&lpar;拖拽,左滑删除,右滑完成&rpar;功能实现(1)

    场景: 近期做的TODO APP需要在主页添加一个功能,就是可以左滑删除,右滑完成.看了一下当前其他人做的例如仿探探式的效果,核心功能基本一样,但是和我预想的还是有少量区别,于是干脆自己重头学一遍如何 ...

  10. js中this是什么?

    this是js的一个关键字 指定一个对象然后去替代他 分两种情况函数内的this和函数外的this 函数内的this指向行为发生的主体 函数外的this都指向window函数内的this跟函数在哪定义 ...