我正在尝试通过JSON encoded
将ajax
字符串发送到PHP文件。
我尝试了这个,但是在{ajax目标文件中$_POST
为空。
var html = $.ajax({
type: "POST",
url: "getControl.php",
data:js_post_array,
dataType: 'json',
async: false,
success: function (data, status)
{
//alert('here');
//$("#notiDesc").text(data.msg);
}
}).responseText;
js_post_array
包含json编码的字符串
{ 'business_name': 'test', 'business_type': 'R', 'type': '', 'total_sku_in_store': '',
'speciality': '', 'first_name': '', 'last_name': '', 'title': '',
'responsible_for_wine_buying': '', 'responsible_for_events': '', 'address1': '' }
但是在getControl.php
文件中,我尝试print_r($_POST)
显示一个空数组。
但是,当我只是复制此字符串并粘贴data:js_post_array,
而不是js_post_array
时,它就能正常工作。
我做错了什么?
答案 0 :(得分:1)
对于发送部分,请执行以下操作:
$.ajax({
url: …,
// Make sure to send data as post body
type: 'POST',
headers: {
// Make sure to send as JSON
'Content-Type': 'application/json',
},
// Serialize your object
data: JSON.stringify(sampleData)
});
对于接收部分:
<?php
// Get the response body (the data is not in $_POST)
$body = file_get_contents('php://input');
print_r(
// Convert JSON string to some PHP data structure (PHP array)
json_decode($body)
);
请注意
答案 1 :(得分:-1)
这是因为data
接受的字符串不是像数组那样的其他数据类型...它只是在URL中将字符串附加为query String
并发送给服务器。
因此,如果你传递一个数组,那么它就不会将其分解为字符串,这就是为什么它会给你空$_POST
答案 2 :(得分:-1)
你确定js_post_array在该函数内是可见的吗?
看起来在ajax调用中创建了一个名为js_post_array的新变量为空。
尝试以这种方式声明js_post_array:
var js_post_array = ....;
var html = $.ajax {
...
}