ker*_*mit 45 javascript php ajax json
如何在浏览器中将JSON数据从Javascript发送到服务器并让PHP在那里解析?
ker*_*mit 56
我在这里得到了很多信息,所以我想发布一个我发现的解决方案.
问题:从浏览器上的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 ...]
Run Code Online (Sandbox Code Playgroud)
4)在服务器上,PHP代码读取JSON字符串:
$str_json = file_get_contents('php://input');
Run Code Online (Sandbox Code Playgroud)
这将读取原始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))
Run Code Online (Sandbox Code Playgroud)
当我通过AJAX/XMLHttpRequest发送str_json时,PHP现在可以填充$ _POST数组,如上面的版本1所示.
显示内容$_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 content-type标头,则必须通过php:// input而不是$ _POST访问PHP中的原始POST数据.
参考文献:
1)如何在PHP中访问POST数据:如何在PHP 中访问POST数据?
2)有关application/json类型的详细信息,其中一些示例对象可以转换为JSON字符串并发送到服务器:http://www.ietf.org/rfc/rfc4627.txt
Cyr*_*lle 16
使用jQuery的javascript文件(清理但库开销):
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
});
Run Code Online (Sandbox Code Playgroud)
PHP文件(process.php):
directions = json_decode($_POST['json']);
var_dump(directions);
Run Code Online (Sandbox Code Playgroud)
请注意,如果您在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);
});
Run Code Online (Sandbox Code Playgroud)
您必须在PHP文件中返回一个JSON对象(以javascript格式),以便在您的Javascript代码中获得"完成/成功"结果.至少返回/打印:
print('{}');
Run Code Online (Sandbox Code Playgroud)
请参阅Ajax请求返回200 OK但是触发了错误事件而不是成功
虽然对于任何更严重的事情,您应该使用适当的响应代码明确地发回适当的标头.
小智 6
关于JavaScript输入字段的JavaScript的简单示例(使用AJAX发送到服务器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>
Run Code Online (Sandbox Code Playgroud)
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>
';
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101897 次 |
| 最近记录: |