你究竟如何使用json_decode将javascript数组传递给php? [英] How exactly do you use json_decode to pass a javascript array to php?
问题描述
这就是我将我的php数组转换为javascript的方式
This is how I got my php array to javascript
echo 'var daysofweek = '.json_encode($daysofweek).';';
现在我知道json_decode可以做相反的事情,但问题是我不知道这样做的语法。
Now I am aware that json_decode can do the opposite, however the problem is I don't know the syntax to do so.
我试过:
<script>
var array_days = new Array();
array_days[] = "psdfo";
array_days[] = "bsdf";
<?php
$array_days = json_decode(?>array_days<?php);?>
</script>
是的,我很无能为力。
我忘记了提到我想通过post发送一个数组,包含有关javascript动态创建的所有表单值的所有信息。否则,我不知道要查找哪个名称=,因为它将由用户决定。除非其他人有替代解决方案...
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...
推荐答案
<script>
var array_days = new Array();
array_days[] = "psdfo";
array_days[] = "bsdf";
<?php
$array_days = json_decode(?>array_days<?php);?>
</script>
我对此部分一无所知......这是javascript ?如果是这样,你需要使用JSON解析器,如JSON2.js https://github.com/douglascrockford/ JSON-js
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 JSON对象,允许您将JSON字符串解析为Javascript对象。 (你总是可以使用eval()但它不会阻止可能的恶意代码......)或者反过来......从Javascript对象转换为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.
转换为JSON字符串后,您只需要通过AJAX将数据发送到PHP文件,例如:
After converting to a JSON string you just need to send the data through AJAX to a PHP file, like:
var data = {
key: value,
key2: value2
},
JSON = JSON.stringify(data);
$.ajax({
url: 'php_file.php',
type: 'POST',
data: JSON,
success: function(data){
alert(data)
}
});
(我使用jQuery保存一些行...)
(I'm using jQuery to save some lines...)
然后在php_file.php上你会有这样的东西:
Then on the php_file.php you would have something like this:
<?php
$json = json_decode($_POST['data']);
foreach($json as $value){
//Do something with it!
}
?>
这篇关于你究竟如何使用json_decode将javascript数组传递给php?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!