将 JSON 数据从 Javascript 发送到 PHP?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8599595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send JSON data from Javascript to PHP?
提问by kermit
How can I send JSON data from Javascript in the browser, to a server and have PHP parse it there?
如何将 JSON 数据从浏览器中的 Javascript 发送到服务器并让 PHP 在那里解析它?
回答by kermit
I've gotten lots of information here so I wanted to post a solution I discovered.
我在这里得到了很多信息,所以我想发布一个我发现的解决方案。
The problem:Getting JSON data from Javascript on the browser, to the server, and having PHP successfully parse it.
问题:从浏览器上的 Javascript 获取 JSON 数据到服务器,并让 PHP 成功解析它。
Environment:Javascript in a browser (Firefox) on Windows. LAMP server as remote server: PHP 5.3.2 on Ubuntu.
环境:Windows 上的浏览器 (Firefox) 中的 Javascript。LAMP 服务器作为远程服务器:Ubuntu 上的 PHP 5.3.2。
What works (version 1):
1) JSON is just text. Text in a certain format, but just a text string.
2) In Javascript, var str_json = JSON.stringify(myObject)
gives me the JSON string.
3) I use the AJAX XMLHttpRequest object in Javascript to send data to the server:
什么有效(版本 1):
1)JSON 只是文本。特定格式的文本,但只是一个文本字符串。
2)在Javascript中,var str_json = JSON.stringify(myObject)
给我JSON字符串。
3)我在Javascript中使用AJAX XMLHttpRequest对象向服务器发送数据:
request= new XMLHttpRequest()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_json)
[... code to display response ...]
4) On the server, PHP code to read the JSON string:
4)在服务器端,读取JSON字符串的PHP代码:
$str_json = file_get_contents('php://input');
This reads the raw POST data. $str_json
now contains the exact JSON string from the browser.
这将读取原始 POST 数据。$str_json
现在包含来自浏览器的确切 JSON 字符串。
What works (version 2):
1) If I want to use the "application/x-www-form-urlencoded"
request header, I need to create a standard POST string of "x=y&a=b[etc]"
so that when PHP gets it, it can put it in the $_POST
associative array. So, in Javascript in the browser:
什么工作(版本 2):
1)如果我想使用"application/x-www-form-urlencoded"
请求头,我需要创建一个标准的 POST 字符串,"x=y&a=b[etc]"
这样当 PHP 得到它时,它可以把它放在$_POST
关联数组中。因此,在浏览器中的 Javascript 中:
var str_json = "json_string=" + (JSON.stringify(myObject))
PHP will now be able to populate the $_POST array when I send str_json via AJAX/XMLHttpRequest as in version 1 above.
Displaying the contents of $_POST['json_string']
will display the JSON string. Using json_decode() on the $_POST array element with the json string will correctly decode that data and put it in an array/object.
当我像上面的版本 1 一样通过 AJAX/XMLHttpRequest 发送 str_json 时,PHP 现在可以填充 $_POST 数组。
显示 的内容$_POST['json_string']
将显示 JSON 字符串。在带有 json 字符串的 $_POST 数组元素上使用 json_decode() 将正确解码该数据并将其放入数组/对象中。
The pitfall I ran into:
Initially, I tried to send the JSON string with the header of application/x-www-form-urlencoded and then tried to immediately read it out of the $_POST array in PHP. The $_POST array was always empty. That's because it is expecting data of the form yval=xval&[rinse_and_repeat]. It found no such data, only the JSON string, and it simply threw it away. I examined the request headers, and the POST data was being sent correctly.
Similarly, if I use the application/json header, I again cannot access the sent data via the $_POST array. If you want to use the application/json content-type header, then you must access the raw POST data in PHP, via php://input, not with $_POST.
我遇到的陷阱:
最初,我尝试发送带有 application/x-www-form-urlencoded 标头的 JSON 字符串,然后尝试立即从 PHP 中的 $_POST 数组中读取它。$_POST 数组始终为空。那是因为它需要 yval=xval&[rinse_and_repeat] 形式的数据。它没有找到这样的数据,只有 JSON 字符串,它只是把它扔掉了。我检查了请求头,POST 数据被正确发送。
同样,如果我使用 application/json 标头,我将再次无法通过 $_POST 数组访问发送的数据。如果要使用 application/json 内容类型标头,则必须通过 php://input 而不是 $_POST 访问 PHP 中的原始 POST 数据。
References:
1) How to access POST data in PHP: How to access POST data in PHP?
2) Details on the application/json type, with some sample objects which can be converted to JSON strings and sent to the server: http://www.ietf.org/rfc/rfc4627.txt
参考资料:
1) 如何在 PHP 中访问 POST 数据:如何在 PHP中访问 POST 数据?
2) application/json 类型的详细信息,以及一些可以转换为 JSON 字符串并发送到服务器的示例对象:http: //www.ietf.org/rfc/rfc4627.txt
回答by Cyrille
Javascript file using jQuery (cleaner but library overhead):
使用 jQuery 的 Javascript 文件(更干净但库开销大):
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
});
PHP file (process.php):
PHP文件(process.php):
directions = json_decode($_POST['json']);
var_dump(directions);
Note that if you use callback functions in your javascript:
请注意,如果您在 javascript 中使用回调函数:
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
})
.done( function( data ) {
console.log('done');
console.log(data);
})
.fail( function( data ) {
console.log('fail');
console.log(data);
});
You must, in your PHP file, return a JSON object (in javascript formatting), in order to get a 'done/success' outcome in your Javascript code. At a minimum return/print:
您必须在 PHP 文件中返回一个 JSON 对象(以 javascript 格式),以便在您的 Javascript 代码中获得“完成/成功”结果。至少返回/打印:
print('{}');
See Ajax request return 200 OK but error event is fired instead of success
请参阅Ajax 请求返回 200 OK 但错误事件被触发而不是成功
Although for anything a bit more serious you should be sending back a proper header explicitly with the appropriate response code.
尽管对于任何更严重的事情,您应该使用适当的响应代码显式地发回适当的标头。
回答by Aconic
Simple example on JavaScript for HTML input-fields (sending to server JSON, parsing JSON in PHP and sending back to client) using AJAX:
使用 AJAX 的 HTML 输入字段的 JavaScript 简单示例(发送到服务器 JSON,在 PHP 中解析 JSON 并发送回客户端):
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<body>
<div align="center">
<label for="LName">Last Name</label>
<input type="text" class="form-control" name="LName" id="LName" maxlength="15"
placeholder="Last name"/>
</div>
<br/>
<div align="center">
<label for="Age">Age</label>
<input type="text" class="form-control" name="Age" id="Age" maxlength="3"
placeholder="Age"/>
</div>
<br/>
<div align="center">
<button type="submit" name="submit_show" id="submit_show" value="show" onclick="actionSend()">Show
</button>
</div>
<div id="result">
</div>
<script>
var xmlhttp;
function actionSend() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var values = $("input").map(function () {
return $(this).val();
}).get();
var myJsonString = JSON.stringify(values);
xmlhttp.onreadystatechange = respond;
xmlhttp.open("POST", "ajax-test.php", true);
xmlhttp.send(myJsonString);
}
function respond() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
</script>
</body>
</html>
PHP file ajax-test.php :
PHP 文件 ajax-test.php :
<?php
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$lName = $response[0];
$age = $response[1];
echo '
<div align="center">
<h5> Received data: </h5>
<table border="1" style="border-collapse: collapse;">
<tr> <th> First Name</th> <th> Age</th> </tr>
<tr>
<td> <center> '.$lName.'<center></td>
<td> <center> '.$age.'</center></td>
</tr>
</table></div>
';
?>
回答by John
PHP has a built in function called json_decode(). Just pass the JSON string into this function and it will convert it to the PHP equivalent string, array or object.
PHP 有一个名为 json_decode() 的内置函数。只需将 JSON 字符串传递给此函数,它就会将其转换为 PHP 等效字符串、数组或对象。
In order to pass it as a string from Javascript, you can convert it to JSON using
为了将其作为字符串从 Javascript 传递,您可以使用以下命令将其转换为 JSON
JSON.stringify(object);
or a library such as Prototype
或者像 Prototype 这样的库
回答by Robin Michael Poothurai
There are 3 relevant ways to send Data from client Side (HTML, Javascript, Vbscript ..etc) to Server Side (PHP, ASP, JSP ...etc)
有 3 种相关的方式可以将数据从客户端(HTML、Javascript、Vbscript .. 等)发送到服务器端(PHP、ASP、JSP 等)
1. HTML form Posting Request (GET or POST).
2. AJAX (This also comes under GET and POST)
3. Cookie
HTML form Posting Request (GET or POST)
HTML 表单发布请求(GET 或 POST)
This is most commonly used method, and we can send more Data through this method
这是最常用的方法,我们可以通过这个方法发送更多的数据
AJAX
AJAX
This is Asynchronous method and this has to work with secure way, here also we can send more Data.
这是异步方法,必须以安全的方式工作,在这里我们也可以发送更多数据。
Cookie
曲奇饼
This is nice way to use small amount of insensitive data. this is the best way to work with bit of data.
这是使用少量不敏感数据的好方法。这是处理少量数据的最佳方式。
In your case You can prefer HTML form post or AJAX. But before sending to server validate your json by yourself or use link like http://jsonlint.com/
在您的情况下,您可以更喜欢 HTML 表单发布或 AJAX。但是在发送到服务器之前自己验证您的 json 或使用像http://jsonlint.com/这样的链接
If you have Json Object convert it into String using JSON.stringify(object), If you have JSON string send it as it is.
如果您有 Json 对象,则使用 JSON.stringify(object) 将其转换为 String,如果您有 JSON 字符串,则按原样发送。
回答by ravi404
I recommend the jquery.post()method.
我推荐jquery.post()方法。
回答by khael
using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php) to parse it in php. And then you can use it as an array.
使用 JSON.stringify(yourObj) 或 Object.toJSON(yourObj) 最后一个用于使用prototype.js,然后使用任何你想要的方式发送它,ajax 或提交,然后按照建议使用 json_decode ( http://www.prototype.js) 。 php.net/manual/en/function.json-decode.php) 在 php 中解析它。然后你可以将它用作数组。
回答by jianfeng
<html>
<script type="text/javascript">
var myJSONObject = {"bindings": 11};
alert(myJSONObject);
var stringJson =JSON.stringify(myJSONObject);
alert(stringJson);
</script>
</html>
回答by Юрий Столов
You can easily convert object into urlencoded string:
您可以轻松地将对象转换为 urlencoded 字符串:
function objToUrlEncode(obj, keys) {
let str = "";
keys = keys || [];
for (let key in obj) {
keys.push(key);
if (typeof (obj[key]) === 'object') {
str += objToUrlEncode(obj[key], keys);
} else {
for (let i in keys) {
if (i == 0) str += keys[0];
else str += `[${keys[i]}]`
}
str += `=${obj[key]}&`;
keys.pop();
}
}
return str;
}
console.log(objToUrlEncode({ key: 'value', obj: { obj_key: 'obj_value' } }));
// key=value&obj[obj_key]=obj_value&
回答by OatMs
I found easy way to do but I know it not perfect
我找到了简单的方法,但我知道它并不完美
1.assign json to
1.将json分配给
if you JSON is
如果你 JSON 是
var data = [
{key:1,n: "Eve"}
,{key:2,n:"Mom"}
];
in ---main.php ----
在 ---main.php ----
<form action="second.php" method="get" >
<input name="data" type="text" id="data" style="display:none" >
<input id="submit" type="submit" style="display:none" >
</form>
<script>
var data = [
{key:1,n: "Eve"}
,{key:2,n:"Mom"} ];
function setInput(data){
var input = document.getElementById('data');
input.value = JSON.stringify(data);
var submit =document.getElementById('submit');
//to submit and goto second page
submit.click();
}
//call function
setInput(data);
</script>
in ------ second.php -----
在 ------ 第二个.php -----
<script>
printJson();
function printJson(){
var data = getUrlVars()["data"];
//decode uri to normal character
data = decodeURI(data);
//for special character , / ? : @ & = + $ #
data = decodeURIComponent(data);
//remove " ' " at first and last in string before parse string to JSON
data = data.slice(1,-1);
data = JSON.parse(data);
alert(JSON.stringify(data));
}
//read get variable form url
//credit http://papermashup.com/read-url-get-variables-withjavascript/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>