[英]passing JavaScript object to PHP not working
I'm trying to send my javascript object to PHP via JSON.stringify()
我正在尝试通过
JSON.stringify()
将我的 javascript 对象发送到 PHP
Javascript: Javascript:
$('#save').on('click touch', function(){
obj = {
"1" : {
"1" : "hey",
"2" : "hay"
},
"2" : {
"1" : "hey",
"2" : "hay"
}
}
var json = JSON.stringify( obj );
console.log(json)
$.ajax({
type: 'POST',
url: 'ajax.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
ajax.php: ajax.php:
<?php
$obj = json_decode($json);
echo $obj;
?>
But this code returns an error saying that $json
is not defined.但是此代码返回一个错误,指出
$json
未定义。 I have no idea why this is not working.我不知道为什么这不起作用。
There are 2 problems.有2个问题。
First, add this*:首先,添加这个*:
$.ajax({
type: 'POST',
url: 'ajax.php',
data : { json: json }, // <---------------------
...
* this works just because jQuery implementation will automatically convert any non-string data argument into a form-urlencoded query string. * 这只是因为 jQuery 实现会自动将任何非字符串数据参数转换为表单 urlencoded 查询字符串。 See the docs .
请参阅文档。
Then, in your PHP, you should do:然后,在您的 PHP 中,您应该执行以下操作:
$jsonStr = $_POST['json'];
$json = json_decode($jsonStr);
Another possible way:另一种可能的方式:
$.ajax({
type: 'POST',
url: 'ajax.php',
data : json , // <---------------------
...
This way, your data will not be a valid form-urlencoded
input, so PHP will not parse it into $_POST
, but you still can get the contents of your input doing this:这样,您的数据将不是有效的
form-urlencoded
输入,因此 PHP 不会将其解析为$_POST
,但您仍然可以通过执行以下操作获取输入的内容:
$jsonStr = file_get_contents("php://input");
$json = json_decode($jsonStr);
Well - you never pass your data in the AJAX request!好吧 - 你永远不会在 AJAX 请求中传递你的数据!
$.ajax({
type: 'POST',
url: 'ajax.php',
data: json //<---- RIGHT HERE
success: function(data) {
alert(data);
$("p").text(data);
}
});
You have to send the obj with the ajax request您必须使用 ajax 请求发送 obj
$.ajax({
type: 'POST',
url: 'ajax.php',
data : json,
dataType : 'json' // for json response
...
Check here for reference jQuery ajax在这里查看参考jQuery ajax
Data parameter : Specifies data to be sent to the server.数据参数:指定要发送到服务器的数据。
Try this:尝试这个:
$('#save').on('click touch', function(){
obj = {
"1" : {
"1" : "hey",
"2" : "hay"
},
"2" : {
"1" : "hey",
"2" : "hay"
}
}
var json = JSON.stringify( obj );
$.ajax({
data : json,
type: 'POST',
url: 'ajax.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
Replace your ajax code with this.用这个替换你的ajax代码。
$.ajax({
type: 'POST',
url: 'ajax.php',
data: json
success: function(data) {
alert(data);
$("p").text(data);
}
});
For ajax php对于 ajax php
<?php
$obj = json_decode($_POST['data']);
echo $obj;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.