gpt4 book ai didi

javascript - AJAX和php JSON连接DB并返回值

转载 作者:行者123 更新时间:2023-11-28 07:31:04 25 4
gpt4 key购买 nike

我是使用 AJAX 的新手,我尝试在单击时创建一个图像按钮,以 JSON 形式从查询返回结果。我制作图像按钮并编写一个 jQuery 来测试它,当我单击以显示警报时,并且在我用 AJAX 替换警报后可以工作,但不起作用。在 php 中与 db 建立连接,执行查询并创建 JSON 数组seee是制作JSON数组的代码

ajax代码

$.ajax({
type: "POST",
url: "routing.php",
data: { data : JSON.stringify(ar)},
dataType : "JSON",
success: function(data){
var jsonAr = JSON.parse(data);
alert(data);


}
});

PHP文件服务器端

//header('Content-Type: application/json');

if(isset($_POST['data'])){
$obj = json_decode($_POST['data']);
//some php operation
}
echo $obj;

代码可以工作,但是从 php 的服务器端给出了这个错误发布http://xxxx/xxxxxx/routing.php [HTTP/1.0 500 内部服务器错误 39ms]

最佳答案

我猜你不需要ajax中的contentType:

contentType: "application/json",

您可以将其删除以进行测试。

<小时/>

默认情况下,这是 jquery ajax 的内容类型:

application/x-www-form-urlencoded

并且您将内容类型设置为:

contentType: "application/json",

所以在后端 php 你不能使用 $_POST["type"]; 因为这种方式不可用,而你必须使用:

$data = json_decode(file_get_contents("php://input"));
$type = $data->type; // will let you get the posted "type"

关于javascript - AJAX和php JSON连接DB并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29121361/

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