[英]JSON string in ajax post request content-type application/formdata vs application/json
It might be a very basic or silly question but its indeed a deep concept question. 这可能是一个非常基本或愚蠢的问题,但实际上确实是一个深层的概念问题。
If I have a ajax post request like (client side): 如果我有一个ajax发布请求,例如(客户端):
var response = {};
response['key'] = value;
response['key2'] = value2;
$.ajax({
type: "POST",
url: "xyz.php",
data: JSON.stringify(response),
dataType: "html",
success: function (result) {}
});
And on server side I do 在服务器端
$a = json_decode($data, true);
And I can $a['abc'] and do rest of my work. 我可以$ a ['abc']来完成其余的工作。
Question is since I have not specified contentType as application/json in ajax request the jquery would send the data as application/form-data which means I should access it via $_POST['data'] and don't do json_decode. 问题是因为我没有在ajax请求中将contentType指定为application / json,因此jquery会将数据发送为application / form-data,这意味着我应该通过$ _POST ['data']访问它,而不执行json_decode。 Right?
对?
Vise Versa If I send json string on client side with content type application/json then on server side I can on access it via json_decode and not $_POST[]. Vise Versa如果我在客户端使用内容类型application / json发送json字符串,那么在服务器端,我可以通过json_decode而不是$ _POST []访问它。 Right?
对?
I'm quiet confused on this basic issue. 我对这个基本问题感到困惑。 Can anyone provide a good explanation on this???
谁能对此提供很好的解释???
Note: My server returns the json encoded data in return. 注意:我的服务器返回json编码的数据作为回报。 And Im using slim framework so I can access the post body as $app->request->getBody();
我使用的是苗条的框架,因此我可以通过$ app-> request-> getBody();访问帖子正文。
If you want all your data to be accessible through a single variable on the server side, you'll want to do something like this: 如果希望通过服务器端的单个变量访问所有数据,则需要执行以下操作:
JS: JS:
$.ajax({
type: "POST",
url: "xyz.php",
data: {'data', JSON.stringify(response)},
dataType: "html",
success: function (result) {}
});
PHP: PHP:
$a = json_decode($_POST['data'], true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.