使用 ajax 将 JSON 发送到 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10955017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending JSON to PHP using ajax
提问by Abdullah Al Shakib
I want to send some data in json format to php and do some operation in php. My problem is i can't send json data via ajax to my php file.Please help me how can i do that. I have tried this way..
我想将一些json格式的数据发送到php并在php中做一些操作。我的问题是我无法通过 ajax 将 json 数据发送到我的 php 文件。请帮助我我该怎么做。我试过这种方法..
<script>
$(function (){
$("#add-cart").click(function(){
var bid=$('#bid').val();
var myqty=new Array()
var myprice=new Array()
qty1=$('#qty10').val();
qty2=$('#qty11').val();
qty3=$('#qty12').val();
price1=$('#price1').val();
price2=$('#price2').val();
price3=$('#price3').val();
var postData =
{
"bid":bid,
"location1":"1","quantity1":qty1,"price1":price1,
"location2":"2","quantity2":qty2,"price2":price2,
"location3":"3","quantity3":qty3,"price3":price3
}
var dataString = JSON.stringify(postData);
$.ajax({
type: "POST",
dataType: "json",
url: "add_cart.php",
data: {myData:dataString},
contentType: "application/json; charset=utf-8",
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
});
});
</script>
And in PHP i use:
在 PHP 中我使用:
if(isset($_POST['myData'])){
$obj = json_decode($_POST['myData']);
//some php operation
}
When in add print_r($_POST) in php file, it shows array(0) {} in firebug.
当在 php 文件中添加 print_r($_POST) 时,它在萤火虫中显示 array(0) {}。
回答by Rocket Hazmat
Lose the contentType: "application/json; charset=utf-8",. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).
失去contentType: "application/json; charset=utf-8",. 您不是将 JSON 发送到服务器,而是发送一个普通的 POST 查询(恰好包含一个 JSON 字符串)。
That should make what you have work.
那应该使你所拥有的工作。
Thing is, you don't need to use JSON.stringifyor json_decodehere at all. Just do:
问题是,您根本不需要使用JSON.stringify或json_decode在这里。做就是了:
data: {myData:postData},
Then in PHP:
然后在 PHP 中:
$obj = $_POST['myData'];
回答by Niet the Dark Absol
That's because $_POSTis pre-populated with form data.
那是因为$_POST预先填充了表单数据。
To get JSON data (or any raw input), use php://input.
要获取 JSON 数据(或任何原始输入),请使用php://input.
$json = json_decode(file_get_contents("php://input"));
回答by Akhan Ismailov
To send javascript obj to php using json and ajax:
使用 json 和 ajax 将 javascript obj 发送到 php:
js:
js:
var dataPost = {
"var": "foo"
};
var dataString = JSON.stringify(dataPost);
$.ajax({
url: 'server.php',
data: {myData: dataString},
type: 'POST',
success: function(response) {
alert(response);
}
});
to use that object in php:
在 php 中使用该对象:
$obj = json_decode($_POST["myData"]);
echo $obj->var;
回答by Tadej
If you want to get the values via the $_POSTvariablethen you should not specify the contentType as "application/json"but rather use the default "application/x-www-form-urlencoded; charset=UTF-8":
如果要通过$_POST变量获取值,则不应指定 contentType"application/json"而是使用默认值"application/x-www-form-urlencoded; charset=UTF-8":
JavaScript:
JavaScript:
var person = { name: "John" };
$.ajax({
//contentType: "application/json", // php://input
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
dataType : "json",
method: "POST",
url: "http://localhost/test/test.php",
data: {data: person}
})
.done(function(data) {
console.log("test: ", data);
$("#result").text(data.name);
})
.fail(function(data) {
console.log("error: ", data);
});
PHP:
PHP:
<?php
// $_POST
$jsonString = $_POST['data'];
$newJsonString = json_encode($jsonString);
header('Content-Type: application/json');
echo $newJsonString;
Else if you want to send a JSON from JavaScript to PHP:
否则,如果您想将 JSON 从 JavaScript 发送到 PHP:
JavaScript:
JavaScript:
var person = { name: "John" };
$.ajax({
contentType: "application/json", // php://input
//contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
dataType : "json",
method: "POST",
url: "http://localhost/test/test.php",
data: person
})
.done(function(data) {
console.log("test: ", data);
$("#result").text(data.name);
})
.fail(function(data) {
console.log("error: ", data);
});
PHP:
PHP:
<?php
$jsonString = file_get_contents("php://input");
$phpObject = json_decode($jsonString);
$newJsonString = json_encode($phpObject);
header('Content-Type: application/json');
echo $newJsonString;
回答by ContextSwitch
I believe you could try something like this:
我相信你可以尝试这样的事情:
var postData =
{
"bid":bid,
"location1":"1","quantity1":qty1,"price1":price1,
"location2":"2","quantity2":qty2,"price2":price2,
"location3":"3","quantity3":qty3,"price3":price3
}
$.ajax({
type: "POST",
dataType: "json",
url: "add_cart.php",
data: postData,
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
the json encode should happen automatically, and a dump of your post should give you something like:
json 编码应该自动发生,你的帖子的转储应该给你类似的东西:
array(
"bid"=>bid,
"location1"=>"1",
"quantity1"=>qty1,
"price1"=>price1,
"location2"=>"2",
"quantity2"=>qty2,
"price2"=>price2,
"location3"=>"3",
"quantity3"=>qty3,
"price3"=>price3
)
回答by ContextSwitch
just remove:
只需删除:
...
//dataType: "json",
url: "index.php",
data: {myData:postData},
//contentType: "application/json; charset=utf-8",
...
回答by xackobo
You are tryng to send js array with js object format.
您正在尝试使用 js 对象格式发送 js 数组。
Instead of use
而不是使用
var a = new array();
a['something']=...
try:
尝试:
var a = new Object();
a.something = ...
回答by Hyman
I know it's been a while, but just in case someone still needs it:
我知道已经有一段时间了,但以防万一有人仍然需要它:
The JSON object I need to pass:
我需要传递的 JSON 对象:
0:{CommunityId: 509, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}
1:{CommunityId: 510, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}
The Ajax code:
阿贾克斯代码:
data: JSON.stringify(The-data-shows-above),
type: 'POST',
datatype: 'JSON',
contentType: "application/json; charset=utf-8"
And the PHP side:
而 PHP 方面:
json_decode(file_get_contents("php://input"));
It works for me, hope it can help!
对我有用,希望能帮到你!

