gpt4 book ai didi

php - 使用 php Ajax 将 json 发送到服务

转载 作者:行者123 更新时间:2023-12-01 04:38:20 24 4
gpt4 key购买 nike

我使用 jquery 使用 ajax 和 php 将数据发布到服务器。

这是客户端代码:

var serverService="http://localhost/service/";
var base_url = serverService+'doing.php';
$.ajax({
type: "POST",
url: base_url,
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"user": "test",
"type": "type 1"
}),
crossDomain: true,
cache: false,
success:function(data)
{
console.log(data);
},
error: function(e) {
console.log(e);
}
});

这是服务器:

$data = json_decode(file_get_contents('php://input'), true);
$result = array();
if(isset($data['user']) && isset($data['type'])){
//do something
}
else{
$result['error'] = "fail";
}
echo json_encode($result, JSON_UNESCAPED_UNICODE);

发帖时,服务器无法识别用户和类型,显示总是返回 fail

请帮助我!

最佳答案

您需要添加如下所述的数据。

来自

data: JSON.stringify({
"user": "test",
"type": "type 1"
}),

data: JSON.stringify({
user: "test",
type: "type 1"
}),

如果不起作用请告诉我。

关于php - 使用 php Ajax 将 json 发送到服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45180711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com