如何将 JSON 数据从浏览器中的 Javascript 发送到服务器并让 PHP 在那里解析它?
将 JSON 数据从 Javascript 发送到 PHP?
我在这里得到了很多信息,所以我想发布一个我发现的解决方案。
问题:从浏览器上的 Javascript 获取 JSON 数据到服务器,并让 PHP 成功解析它。
环境: Windows 上浏览器 (Firefox) 中的 Javascript。LAMP 服务器作为远程服务器:Ubuntu 上的 PHP 5.3.2。
什么有效(版本 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)在服务器端,读取JSON字符串的PHP代码:
$str_json = file_get_contents('php://input');
这将读取原始 POST 数据。$str_json
现在包含来自浏览器的确切 JSON 字符串。
什么工作(版本 2):
1)如果我想使用"application/x-www-form-urlencoded"
请求头,我需要创建一个标准的 POST 字符串,"x=y&a=b[etc]"
这样当 PHP 得到它时,它可以把它放在$_POST
关联数组中。因此,在浏览器中的 Javascript 中:
var str_json = "json_string=" + (JSON.stringify(myObject))
当我像上面的版本 1 一样通过 AJAX/XMLHttpRequest 发送 str_json 时,PHP 现在将能够填充 $_POST 数组。
显示 的内容$_POST['json_string']
将显示 JSON 字符串。在带有 json 字符串的 $_POST 数组元素上使用 json_decode() 将正确解码该数据并将其放入数组/对象中。
我遇到的陷阱:
最初,我尝试发送带有 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 数据。
参考资料:
1) 如何在 PHP 中访问 POST 数据:如何在 PHP中访问 POST 数据?
2) application/json 类型的详细信息,以及一些可以转换为 JSON 字符串并发送到服务器的示例对象:http : //www.ietf.org/rfc/rfc4627.txt
使用 jQuery 的 Javascript 文件(更干净但库开销更大):
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
});
PHP文件(process.php):
directions = json_decode($_POST['json']);
var_dump(directions);
请注意,如果您在 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);
});
您必须在您的 PHP 文件中返回一个 JSON 对象(以 javascript 格式),以便在您的 Javascript 代码中获得“完成/成功”结果。至少返回/打印:
print('{}');
请参阅Ajax 请求返回 200 OK 但错误事件被触发而不是成功
尽管对于任何更严重的事情,您应该使用适当的响应代码明确发送回适当的标头。
使用 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 文件 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>
';
?>
PHP 有一个名为 json_decode() 的内置函数。只需将 JSON 字符串传递给此函数,它就会将其转换为 PHP 等效字符串、数组或对象。
为了将其作为字符串从 Javascript 传递,您可以使用以下命令将其转换为 JSON
JSON.stringify(object);
或者像 Prototype 这样的库
有 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 表单发布请求(GET 或 POST)
这是最常用的方法,我们可以通过这个方法发送更多的数据
AJAX
这是异步方法,必须以安全的方式工作,在这里我们也可以发送更多数据。
曲奇饼
这是使用少量不敏感数据的好方法。这是处理少量数据的最佳方式。
在您的情况下,您可以更喜欢 HTML 表单发布或 AJAX。但是在发送到服务器之前,请自己验证您的 json 或使用像http://jsonlint.com/这样的链接
如果您有 Json 对象,则使用 JSON.stringify(object) 将其转换为 String,如果您有 JSON 字符串,则按原样发送。