Post Json String get NULL
我已将表单的所有条目转换为对象,然后使用该对象填充它以填充数组:
var jsonObj = []; var formData = new FormData(); $('[name="'+form+'"] *').not(':input[type=file], :input[type=button], :input[type=submit], :input[type=reset], [name="input_search"]').filter(':input').each(function(obj, v) { var iObj = {} var input = $(this); var inputname = input.attr("name"); var val = input.val(); var inputval = val; iObj[inputname] = inputval; jsonObj.push(iObj); });
后来我尝试使用以下方法将Final数组转换为Json String:
jsonData = JSON.stringify(jsonObj);
我得到这个字符串:
[{"s-file[]":"Prueba 3"},{"text_file[]":"ORT0000133.pdf"},{"idform":"f-gen-desk"},{"idprocess":"p-save"}]
我发送给PHP服务器这个,因为我发送其他元素类型文件与formData.append
方法:
formData.append('jsonData', jsonData); var url = 'index.php'; $.ajax({ url: url, data: formdata, contentType: false, processData: false, type: 'POST', cache: false, error: function(xhr, status, error) { alert(error); }, success: function(response) { alert(response); } });
在PHP服务器端我尝试获取此字符串:
echo var_dump($_POST['jsonData']);
我得到这个字符串:
string(169) "[{"s-file[]":"Prueba 3"},{"text_file[]":"ORT0000133.pdf"},{"idform":"f-gen-desk"},{"idprocess":"p-save"}]"
当我尝试将此转换为和Array时:
测试1:
echo '
'; echo var_dump($_POST); echo '';
输出继电器:
array(1) { ["jsonData"]=> string(169) "[{"s-file[]":"Prueba 3"},{"text_file[]":"ORT0000133.pdf"},{"idform":"f-gen-desk"},{"idprocess":"p-save"}]" }
测试2:
echo '
'; $jsonData=$_POST['jsonData']; $Data=json_decode($jsonData); echo var_dump($Data); echo '';
输出:我得到
NULL
。我不明白我做错了什么
最后更新:
我运行这个测试:
echo '
'; $jsonData = '|'.$_POST['jsonData'].'|'; $json = '|'.'[{"s-file[]":"Prueba 3"},{"text_file[]":"casa.jpg"},{"idform":"f-gen-desk"},{"idprocess":"p-save"}]'.'|'; echo $Line = mb_strlen(mb_strcut($jsonData, 0, strspn($jsonData ^ $json, "\0"))); echo '
'; echo $jsonData[$Line]; echo '
'; echo $json[$Line]; echo '
'; echo '';
产量
3 & "
我可以确定链是腐败的,但我不知道为什么,如何或如何解决它。
发送json的更简单方法是:
$.ajax({ url: url, data: jsonData, // stringified JSON contentType: 'application/json', // processData: false, type: 'POST', //cache: false, POST won't cache error: function(xhr, status, error) { alert(error); }, success: function(response) { alert(response); } });
并在PHP中收到
$data = json_decode(file_get_contents('php://input')[,boolean to force array]);
一般发送数据的最简单方法是在表单上使用
serialize()
并作为默认内容类型发送并接收各种字段$_POST[inputName]
问题可能与使用:
$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING); $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
https://stackoverflow.com/a/9854121/963200
在从
POST
和GET
读取数据后,需要解决它的问题