发送JSON(jQuery的),以PHP和对其进行解码 [英] Sending JSON(jQuery) to PHP and decoding it

查看:115
本文介绍了发送JSON(jQuery的),以PHP和对其进行解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能为我的生命找出我做错了。现在看来似乎应该是简单的,因为我无法找到任何人有这个问题,但我想不出来通过JavaScript(jQuery的)发送的基本数据,PHP和去$ C C是$。为简单起见,这就是我的:

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
    });

和我的PHP文件

$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');

我得到它的单词测试,但无论我做什么,我不明白JSON数据我发送的文件。

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.

是否有人可以分享A到Z由于彻底例子的任何帮助。

Can someone please share a thorough example of A to Z. Thanks for any help.

推荐答案

这是你与jQuery将发送参数'名',值'李四',而不是整个对象的Ajax请求。如果您要发送的整个对象,你必须通过这样的:

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:

data: { parameters: json_data }

在PHP端,你可以从全局变量$ _POST变量。使用你的例子,你可以使用:

On the PHP side, you can get the variables from the $_POST superglobal. Using your example, you would use:

$name = $_POST['name'];

或者,如果你发送的整个对象,用我的例子:

Or, if you send the whole object, using my example:

$params = $_POST['parameters'];

有没有必要使用json_de code(),因为参数从$ _POST数组中拉出来将是本地PHP变量了。

There is no need to use json_decode(), since the parameters you pull out from the $_POST array will be native PHP variables already.

您只需要使用它,如果你有一个JSON字符串,要变成一个PHP变量,这是不是这里的情况,因为jQuery将改造的JavaScript对象,在查询字符串背景。

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.

这是你需要从JavaScript的JSON形式发送数据的情况很少见,但如果你想这样做,你需要的是这样的:

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:

// JS

var person = "{ name: 'John Doe' }"; // notice the double quotes here, this is a string, and not an object
$.ajax({
    type: "POST",
    url: "../bin/process.php",
    dataType: "json",
    data: { json: person }
    });

// PHP

$json = $_POST['json']; // $json is a string
$person = json_decode($json); // $person is an array with a key 'name'

这篇关于发送JSON(jQuery的),以PHP和对其进行解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆