将 JSON(jQuery) 发送到 PHP 并对其进行解码
我一生都无法弄清楚我做错了什么。看起来它应该很简单,因为我找不到其他人遇到这个问题,但我无法弄清楚如何通过 javascript(jQuery) 将基本数据发送到 PHP 并对其进行解码。为了简单起见,这就是我所拥有的:
JAVASCRIPT
var json_data = { "name" : "john doe" };
$.ajax({
type: "POST",
url: "../bin/process.php",
dataType: "json",
data: json_data
});
和我的 PHP 文件
$arr = json_decode("json_data", true);
$fp = fopen('data.txt', "w");
fwrite($fp, $arr['name']);
fclose($fp);
我正在编写的文件最终什么也没有。如果我执行以下操作:
fwrite($fp, 'test');
我会得到一个包含单词 test 的文件,但无论我做什么,我都不会收到我发送的 json 数据。
有人可以分享一个从 A 到 Z 的完整示例吗?感谢您的帮助。
I can't for the life of me figure out what I'm doing wrong. It seems like it should be simple because I can't find anyone else with this issue but I can't figure out to send basic data via javascript(jQuery) to PHP and decode it. For the sake of simplicity, this is what I have:
JAVASCRIPT
var json_data = { "name" : "john doe" };
$.ajax({
type: "POST",
url: "../bin/process.php",
dataType: "json",
data: json_data
});
and my PHP FILE
$arr = json_decode("json_data", true);
$fp = fopen('data.txt', "w");
fwrite($fp, $arr['name']);
fclose($fp);
The file I'm writing ends up with nothing in it. If I do an:
fwrite($fp, 'test');
I get a file with the word test in it but no matter what I do I don't get the json data I sent.
Can someone please share a thorough example of A to Z. Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 jQuery 发出的 ajax 请求将发送参数“name”,值为“john doe”,而不是整个对象。如果你想发送整个对象,你必须像这样传递它:
在 PHP 端,你可以从 $_POST 超全局中获取变量。使用您的示例,您将使用:
或者,如果您发送整个对象,则使用我的示例:
无需使用 json_decode(),因为您从 $_POST 数组中提取的参数已经是本机 PHP 变量。
如果您有一个 json 字符串,您想将其转换为 PHP 变量,那么您只需要使用它,但这里不是这种情况,因为 jQuery 会在后台将 javascript 对象“转换”为查询字符串。
在极少数情况下,您需要以 JSON 形式从 javascript 发送数据,但如果您想这样做,您需要类似以下内容:
The ajax request that you make with jQuery will send the parameter 'name', with the value 'john doe', and not the whole object. If you want to send the whole object, you have to pass it like this:
On the PHP side, you can get the variables from the $_POST superglobal. Using your example, you would use:
Or, if you send the whole object, using my example:
There is no need to use json_decode(), since the parameters you pull out from the $_POST array will be native PHP variables already.
You only need to use it, if you have a json string, which you want to turn into a PHP variable, which is not the case here, since jQuery will "transform" the javascript object, to a query string in the background.
It is a rare case that you need to send data from javascript in a JSON form, but if you want to do that you need something like:
jQuery 无法将数据编码为 JSON,只能对其进行解码(名称不佳的
dataType
参数实际上指的是响应的类型)。使用 json2.js 进行编码。jQuery cannot encode data to JSON, only decode it (the poorly named
dataType
parameter actually refers to the type of the reponse). Use json2.js for encoding.