如何将数据json从javascript解析到php [英] how to parsing data json from javascript to php
问题描述
我想将json从javascript解析为php 这是我的JavaScript代码
i want to parsing json from javascript to php this my javascript code
var Dataconvert;
var asetid = new Array();
$("#simpanmodifikasi").click(function(){
var table = $('#tableasal tbody');
table.find('tr').each(function (row, input) {
// var coba = $(this).find('input'),
// asetid = coba.eq(0).val();
asetid[row] = {
"asetid" : $(this).find('input:eq(0)').val(),
"namabarang" : $(this).find('input:eq(1)').val(),
}
Dataconvert = $.toJSON(asetid);
$.ajax({
url:"<?php echo site_url('fixed/modification/tes');?>",
type:"POST",
data:Dataconvert,
dataType : 'json',
cache : false,
success:function(html){
alert(html);
}
})
});
})
如何在php中解析此json ????,我是javascript和json的新手, 我感谢您的帮助
how to parsing this json in php ???, i am new in javascript and json, i appreciate your help
推荐答案
首先,您需要将$.toJSON(asetid)
更改为JSON.stringify(asetid)
.
但是,如果仍然要使用$.toJSON(asetid)
,则需要包含
First, you need to change $.toJSON(asetid)
to JSON.stringify(asetid)
.
But, if, somehow you still want to use $.toJSON(asetid)
, you need to include the jquery-json
plugin from http://code.google.com/p/jquery-json/ on your page.
第二,我认为ajax请求部分应该放在迭代器函数的外部,否则,您将对表的每一行进行ajax请求. 这是修改后的代码:
Second, I think the ajax request part should be put outside of the iterator function, otherwise, you will be making an ajax request for each row of the table. Here is the revised code:
var Dataconvert;
var asetid = new Array();
$("#simpanmodifikasi").click(function(){
var table = $('#tableasal tbody');
table.find('tr').each(function (row, input) {
// var coba = $(this).find('input'),
// asetid = coba.eq(0).val();
asetid[row] = {
"asetid" : $(this).find('input:eq(0)').val(),
"namabarang" : $(this).find('input:eq(1)').val(),
}
});
//these should be outside the 'each' iterator
Dataconvert = JSON.stringify(asetid);
$.ajax({
url:"<?php echo site_url('fixed/modification/tes');?>",
type:"POST",
data:Dataconvert,
dataType : 'json',
cache : false,
success:function(html){
alert(html);
}
})
})
第三,现在是您问题的答案. ajax请求将在POST正文中发送字符串化的JSON. 示例:
Third, now the answer to your question. The ajax request will send the stringified JSON in the POST body. Example:
[{"asetid":"10","namabarang":"Buku"},{"asetid":"30","namabarang":"Laptop"}]
要从PHP端(fixed/modification/tes
脚本)读取它,可以从标准输入中手动读取它,并使用json_decode
对其进行解析.
To read it from the PHP side (the fixed/modification/tes
script), you can manually read it from the standard input and parse it using json_decode
.
<?php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
?>
这将导致如下结果:
Array
(
[0] => Array
(
[asetid] => 10
[namabarang] => Buku
)
[1] => Array
(
[asetid] => 30
[namabarang] => Laptop
)
)
这篇关于如何将数据json从javascript解析到php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!