您究竟如何使用 json_decode 将 javascript 数组传递给 php?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4543660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:03:34  来源:igfitidea点击:

How exactly do you use json_decode to pass a javascript array to php?

phpjavascript

提问by Adam

This is how I got my php array to javascript

这就是我如何将我的 php 数组转换为 javascript

echo 'var daysofweek = '.json_encode($daysofweek).';';

Now I am aware that json_decode can do the opposite, however the problem is I don't know the syntax to do so.

现在我知道 json_decode 可以做相反的事情,但是问题是我不知道这样做的语法。

I tried:

我试过:

<script>
var array_days = new Array();

array_days[] = "psdfo";
array_days[] = "bsdf";

<?php
$array_days = json_decode(?>array_days<?php);?>

</script>

yes im clueless.

是的,我一无所知。

I forgot to mention that I want to send an array through post, having all my information regarding all the form values dynamically created by javascript. Otherwise, I wouldn't know which name="" to look for as it will be decided by the user. Unless someone else has an alternative solution...

我忘了提到我想通过 post 发送一个数组,其中包含有关由 javascript 动态创建的所有表单值的所有信息。否则,我不知道要查找哪个 name="",因为这将由用户决定。除非其他人有替代解决方案......

采纳答案by Couto

<script>
var array_days = new Array();

array_days[] = "psdfo";
array_days[] = "bsdf";

<?php
$array_days = json_decode(?>array_days<?php);?>

</script>
<script>
var array_days = new Array();

array_days[] = "psdfo";
array_days[] = "bsdf";

<?php
$array_days = json_decode(?>array_days<?php);?>

</script>

I'm clueless in this part... is this javascript? if so, you need to use a JSON Parser like the JSON2.js https://github.com/douglascrockford/JSON-js

我在这部分一无所知......这是javascript吗?如果是这样,您需要使用像 JSON2.js https://github.com/douglascrockford/JSON-js这样的 JSON 解析器

this file creates a Javascript JSON Object which allows you to parse a JSON string to a Javascript object. (you can always use eval() but it won't prevent against possible malicious code...) or the other way around... from a Javascript Object transform into a JSON string.

此文件创建一个 Javascript JSON 对象,它允许您将 JSON 字符串解析为 Javascript 对象。(你总是可以使用 eval() 但它不会阻止可能的恶意代码......)或者相反......从一个 Javascript 对象转换为一个 JSON 字符串。

After converting to a JSON string you just need to send the data through AJAX to a PHP file, like:

转换为 JSON 字符串后,您只需要通过 AJAX 将数据发送到 PHP 文件,例如:

var data = {
   key: value,
   key2: value2 
},
JSON = JSON.stringify(data);

$.ajax({
    url: 'php_file.php',
    type: 'POST',
    data: JSON,
    success: function(data){
        alert(data)
    }
});

(I'm using jQuery to save some lines...)

(我使用 jQuery 来保存一些行......)

Then on the php_file.php you would have something like this:

然后在 php_file.php 上你会有这样的东西:

<?php 
    $json = json_decode($_POST['data']);

    foreach($json as $value){
       //Do something with it!
    }
?>

回答by wajiw

PHP is a pre-processor and can't do what you're asking. You would need the PHP engine to be able to process the javascript on the page. json_decode is for decoding a json string in PHP.

PHP 是一个预处理器,不能满足您的要求。您需要 PHP 引擎才能处理页面上的 javascript。json_decode 用于解码 PHP 中的 json 字符串。

To do that you would have to pass the javascript array to a PHP script using something like Ajax so your PHP script can process it anyway you would need, then pass back the result to your Javascript code.

为此,您必须使用 Ajax 之类的东西将 javascript 数组传递给 PHP 脚本,这样您的 PHP 脚本就可以根据需要处理它,然后将结果传回给您的 Javascript 代码。

回答by Chetan Sharma

Yes as the Wajiw said, PHP is pre-processor. But I think it might be possible with the ajaxed request. Send the Javascript array as an argument request to the other page and process it with the php, and again display back the results.

是的,正如 Wajiw 所说,PHP 是预处理器。但我认为 ajaxed 请求可能是可能的。将 Javascript 数组作为参数请求发送到另一个页面并使用 php 处理它,并再次显示返回结果。

Note: Never tried this :) Thanks

注意:从未尝试过:)谢谢

回答by PleaseStand

First of all:

首先:

array_days[] = "psdfo";
array_days[] = "bsdf";

These lines are valid PHP but not valid JavaScript. The correct equivalent would be:

这些行是有效的 PHP 但不是有效的 JavaScript。正确的等价物是:

array_days.push("psdfo");
array_days.push("bsdf");

On to passing the resulting array of strings(that's what I am assuming) to PHP. To send it as form data in pure JS, we can create hidden input elements when the form is submitted (try it):

将生成的字符串数组(这就是我假设的)传递给 PHP。要在纯JS中将其作为表单数据发送,我们可以在提交表单时创建隐藏的输入元素(试试看):

<form id="myform" method="POST" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi">
    <input type="submit" value="Submit">
</form>
<script>
    document.getElementById('myform').onsubmit = function() {
        for(var i = 0; i < array_days.length; ++i) {
            var inputElement = document.createElement('input');
            inputElement.type = 'hidden';
            inputElement.name = 'array_days[]';
            inputElement.value = array_days[i];
            this.appendChild(inputElement);
        }
    };
</script>

PHP will interpret each input having the name of array_days[]as an array element of $_POST['array_days']. For example, you can access $_POST['array_days'][0]in PHP.

PHP 会将名称array_days[]为 的每个输入解释为 的数组元素$_POST['array_days']。例如,您可以$_POST['array_days'][0]在 PHP 中访问。

For AJAX, jQuery 1.4 and above will automaticallyachieve this effect when you pass an array as a data parameter to $.ajax.

对于AJAX,jQuery的1.4和以上会自动传递时的阵列作为数据参数来达到这种效果$.ajax

Why not json_decode()?The answer is that older versions of web browsers do not support the JavaScript function JSON.stringify()that is equivalent to PHP's json_encode(), although there is a library to add support. One might consider it for a more complex case, but for such a simple case, it should not be necessary.

为什么不json_decode()呢?答案是旧版本的 Web 浏览器不支持与JSON.stringify()PHP 等效的 JavaScript 功能json_encode(),尽管有一个库可以添加支持。对于更复杂的情况,人们可能会考虑它,但对于如此简单的情况,应该没有必要。