[英]Send JSON to PHP and get a response
I'm just learning how to use jQuery and PHP together. 我正在学习如何一起使用jQuery和PHP。 This is my first attempt, and I feel like I'm almost getting the concept.
这是我的第一次尝试,我觉得自己快要明白了。 However, there's an issue I failed to address.
但是,我没有解决一个问题。 When I post a JSON object to PHP script and try to return one of the parameters, I get the following error : "Trying to get property of non-object in ..."
当我向PHP脚本发布JSON对象并尝试返回参数之一时,出现以下错误:“试图在...中获取非对象的属性”
index.html: index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css"></style>
</head>
<body>
<button onClick="postData();">Submit me!</button>
<script>
function postData() {
var myData = {
'firstName' : 'John',
'lastName' : 'Doe'
};
$.ajax( {
type: "POST",
url: "postData.php",
contentType: "application/json",
data: myData,
success: function(msg){
alert(msg);
},
error: function(err) {
alert('error!' + err);
}
});
}
</script>
</body>
</html>
postData.php: postData.php:
<?php
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
$output = $jsonData->{'firstName'};
echo $output;
?>
With a bit more work, you can achieve this using a REST client that will automatically handle data-type conversion and URL parsing among other things. 通过更多的工作,您可以使用REST客户端实现此目的,该客户端将自动处理数据类型转换和URL解析等操作。
To name some of the advantages of using a REST architecture: 列举使用REST体系结构的一些优点:
Simple. 简单。
You can easily scale your solution using caching, loading-balancing etc. 您可以使用缓存,负载平衡等轻松扩展解决方案。
Allows you to logically separate your URL-endpoints. 允许您在逻辑上分隔URL端点。
It gives you the flexibility to change implementation easily without changing clients. 它使您可以灵活地轻松更改实施而无需更改客户端。
Try reading, A Brief Introduction to REST to get a better idea about the design pattern and it's uses. 尝试阅读REST简介,以更好地了解设计模式及其用途。 Of course you won't need to write a framework from scratch if you don't want to, since there are already several open-source PHP based implementations out there such as Recess PHP Rest Framework .
当然,如果您不想的话,也不需要从头开始编写框架,因为那里已经有一些基于PHP的开源实现,例如Recess PHP Rest Framework 。
Hope this helps! 希望这可以帮助!
json_decode
(depending on PHP version) defaults to returning an array, not an object. json_decode
(取决于PHP版本)默认为返回数组,而不是对象。 The proper way to access it would be: 访问它的正确方法是:
$output = $jsonData['firstname'];
You'll also want it to return an associative array, so pass true
as the second argument of json_decode. 您还希望它返回一个关联数组,因此将
true
作为json_decode的第二个参数传递。
$jsonData = json_decode($input, true);
What could alternately be happening is that the JSON is invalid, in which case PHP returns null
. 另一种可能是JSON无效,在这种情况下,PHP返回
null
。 You can check for that: 您可以检查一下:
if ($jsonData = json_decode($input, true) === null) {
// Do stuff!
} else {
// Invalid JSON :(
}
I put it a little bit more simple with the function post of jquery. 我用jquery的函数发布将它简化了一点。 I hope you found it useful:
希望你觉得它有用:
first your html and js: 首先你的HTML和JS:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css">
</style>
</head>
<body>
<button onClick="postData();">Submit me!</button>
<script>
function postData() {
$.post(
"postData.php",
{
firstName : 'John',
lastName : 'Doe'
},
function(msg)
{
alert(msg);
}
);
}
</script>
</body>
</html>
then your php: 然后你的PHP:
<?php
echo $_REQUEST['firstName']." - ".$_REQUEST['lastName'];
?>
I finally figured it out: 我终于想通了:
js: js:
function postData() {
var myData = {
firstName: 'John',
lastName: 'Doe'
};
$.ajax({
type: "POST",
url: "postData.php",
data: JSON.stringify(myData),
success: function(msg){
alert(msg);
},
error: function(err){
alert('error!' + JSON.stringify(err));
}
});
}
php: 的PHP:
<?php
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
$output = $jsonData->{'firstName'};
echo $output;
?>
When decoding you DON'T want to put "true" as the second argument, because then, it's not JSON but an associative array (or so I've read). 解码时,您不想将“ true”作为第二个参数,因为那样的话,它不是JSON而是关联数组(或者我已经读过)。 If I put json_decode($input, true), then it won't work.
如果我放入json_decode($ input,true),那么它将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.